zoukankan      html  css  js  c++  java
  • Hibernate中用proxy(代理)实现类的延迟加载

    可以在.xml文件中指定lazy=”true”这个属性来实现: 
     
    <class name="com.test.Student" table="student" lazy="true"> 这种方式等价于
    <class name="com.test.Student" table="student" proxy="com.test.Student">
     
    这样Hibernate就会自动继承Student这个类,来生成一个代理类,这个代理类是实现延迟加载的关键,

    比如一个Student类有很多属性,所以就希望当用到Student的属性的时候(调用getXXX())才去数据库读取,

    这个时候时候就可以使用Student的代理类如StudentProxy来实现Student的延迟加载!
     
    Student student =  (Student)session.load(Student.class, id);   //如果使用proxy的话,

    Hibernate在执行这句话的时候根本就不会去执行select操作,而这句话的作用仅仅是用cglib来初始化代理类(setSid(id)...)。
     
    student.getSname();       //当执行这句化的时候,Hibernate才会去执行select操作,读取数据库,如下是Hibernate执行此句时候输出的sql
    Hibernate: select student0_.sid as sid0_, student0_.sname as sname0_, student0_.sage as sage0_ from student student0_ where student0_.sid=?

     
    实现原理:proxy其实和JDK1.3的动态代理没有什么区别,只不过JDK1.3的动态代理只能代理接口,而我们在应用Hibernate的时候要代理类,

    所以必须用cglib来实现动态代理类的功能。
     
    下面用JDK的Dynamic Proxy大概说明一下实现过程,大致代码如下:
     
    package com.test;
     
    import java.lang.reflect.Proxy;  
        import java.lang.reflect.InvocationHandler;  
        import java.lang.reflect.Method;    
     
    public class ProxyTest implements InvocationHandler
        {
            public Student student;

        public ProxyTest(Student student)
            {  
                this.student = student;
            }
        public static Student getStudent(Student student)
            {
                return (Student)(Proxy.newProxyInstance(Student.class.getClassLoader(),new Class[]{Student.class},new StudentProxy(student))); 
            }

            public Object invoke(Object proxy, Method m, Object[] args) throws Throwable 
            {
                Object obj = null;
           
                if(“getSname”.equals(m.getSname()))    //当执行的方法为getSname()的时候,就从数据库加载Student类
                {
                    loadById();   //执行select操作;
                 obj = m.invoke(student, args);   
                }
                else
                     obj = m.invoke(student, args);    
                return obj;
            }
    }


    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/luedipiaofeng/archive/2007/07/04/1678574.aspx

  • 相关阅读:
    php实现上传图片保存到数据库的方法
    支付宝集成——如何在回调地址中使用自定义参数
    QQ音乐的各种相关API
    xampp默认mysql密码设置,修改mysql的默认空密码
    node.js 初体验
    php调用empty出现错误Can't use function return value in write context
    ecshop数据库操作函数
    ecshop中$user对象
    为什么我的联想打印机M7450F换完墨粉之后打印机显示请更换墨粉盒?这是我的墨盒第一次灌粉·、
    PHP中获取当前页面的完整URL
  • 原文地址:https://www.cnblogs.com/liuhouhou/p/2976128.html
Copyright © 2011-2022 走看看