用户登录
用户注册

分享至

hibernate解决懒加载

  • 作者: 内涵英雄
  • 来源: 51数据库
  • 2020-11-04
第一种:
1.在需要禁用懒加载的映射文件中显示的加入lazy = "false"
这个方法大大的降低了程序的运行效率,如果访问量小还是可以的
第二种:
2.在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>

这是一个一劳永逸解决懒加载问题的办法.使用spring的openSessionInViewFilter.
openSessionInViewFilter,改过滤器在view渲染时始终开启session,一劳永逸解决hibernate的懒加载问题,
该过滤器必须配置在struts2过滤器之前,如果访问增大性能会降低不推荐使用(性能问题)
第三种:
3.强行在service层面是初始化代理对象.
就是在获取对象之后,强行去加载对象中属性集合(推荐)
例如:
public Department getDepartmentWithChildren(Integer id){
Department s = DepartmentDao.getEntity(id);
//强行初始化pages和questions集合
for(Student stu : s.getStudents()){
stu.getClasses.size();
}
return s;
}
软件
前端设计
程序设计
Java相关