Hibernate懒加载好处



Hibernate懒加载Hibernate懒加载
1.强制初始化(假如Employee中有  Department  的外键,那我们强制初始化 Department  ,就可以在  Employee  中得到  Department    对象的数据  

String hql=”from Employee Where id=? and password=?”;
String parameter[]={emp.getId()+”",emp.getPassword()};
Session session=sf.getCurrentSession();
emp=(Employee) session.createQuery(hql).setString(0, parameter[0]).setString(1, parameter[1]).uniqueResult();
Hibernate.initialize(Department.class);
2.在对象映射文件中配置lazy=”false”一般在one的一方设置,依然在 Department   的映射文件中设置让它关闭懒加载

<hibernate-mapping package=”com.ru.domain”>
<class name=”Department” table=”department” lazy=”false”>


上面方法问题是: 不管你在jsp中使不使用 部门的名称,它都有向数据库发出select 请求.

3.    spring专门提供了opensessioninview的方法来解决懒加载.
OpenSessionInViewFilter调用流程: request(请求)->open session并开始 transaction->controller->View(Jsp)->结束transaction 并 close session.

需要在web.xml文件中添加如下配置:

<filter>

       <filter-name>OpenSessionInViewFilter</filter-name>

       <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>


</filter>

<filter-mapping>

       <filter-name>OpenSessionInViewFilter</filter-name>

       <url-pattern>/*</url-pattern>

</filter-mapping>

该方法可以有效的减少对数据库的查询,缺点是和数据保持的session,时间延长了.