Hibernate懒加载机制(转)

原文来源:http://blog.csdn.net/zhang6622056/article/details/7694176

                  http://superleo.iteye.com/blog/243322/

在关系模型的对应关系中一对一、一对多、和多对多。都已经做了相关案例Hibernate在提供这些查询的时候它有一种懒加载的机制。比如:  之前我们举例的一对一的案例Person-Idcard。如果我们只查询person那么会不会查询Idcard呢? 

public class Person {  

    private int id;  

    private String name;  

    private IdCard idcard; 

}  
 

毕竟Idcard也是Person类的一个属性。如上面的代码: 

如果我们查询一个person我们只是用到了这个person的name属性。而用不到它关联的idcard部分。那么我们就可以在配置文件中设置lazy=”true”的一个选项。如下面的代码: 

<hibernate-mapping   

    package="cn.hibernate.model">  

    <class name="Person" table="person">  

      <id name="id">  

          <generator class="native" /> 

        </id>  

        <property name="name" column="name"/>  

        <!-- 一对一的对象关系描述 -->  

        <one-to-one name="idcard" lazy="false"/>  

    </class> 

</hibernate-mapping>
 

 

当懒加载开启的时候那么我们查询person对象不会去查询相应的Idcard。只有在我们用person对象的get方法调用idcard对象的时候才会执行查询。这样就提高了效率。  

   

举例sql说明: 

下面的这些代码只是查询Emp员工对象。   

   s = HibernateUtil.getSession();  

   Employee emp = (Employee) s.get(Employee.class, 2);  
 

懒加载开启: 

只输出一句sql: 

select employee0_.id as id2_0_, employee0_.empname as empname2_0_, employee0_.dept_id as dept3_2_0_ from employee employee0_ where employee0_.id=? 
 

懒加载未开启: 

输出两句查询sql: 

Hibernate: select employee0_.id as id2_0_, employee0_.empname as empname2_0_, employee0_.dept_id as dept3_2_0_ from employee employee0_ where employee0_.id=?  
Hibernate: select dept0_.id as id1_0_, dept0_.deptname as deptname1_0_ from dept dept0_ where dept0_.id=? 
 

注意:  懒 加载的对象是代理对象,getId是不用访问数据库的。另外getClass得到的也是一个代理对象。只有get其他属性的时候才会访问数据库。 Session的load方法可以懒加载。然后用Hibernate.initialize(proxyObj)load方法实例化该代理对象。    懒加载通过asm和cglib包实现。 

猜你喜欢

转载自wzf7065.iteye.com/blog/2186695
今日推荐