hibernate懒加载问题

[size=small]
----------------------------------------------------------
懒加载可以提高性能吗?
不可以简单的说"能",因为Hibernate的关系映射拖累了SQL的性能,所以想出懒加载来弥补.只是弥补而以,不会超越.所以大家不要想着使用了懒加载总体性能就提高了,其实总体性能不下降就万幸了.
----------------------------------------------------------
Hibernate的lazy属性可以配置在:

(常用)<set><list>标签上
,可以取值true,false,extra
默认为true,当为true时,会懒加载,访问集合属性时再发出SQL语句.但set.size()时,很不智能,不会生成count()语句,而是查出所有记录赋值给set.
extra说明:调用集合的set.size()时,会生成select count(*)from tableName,比较智能.建议使用
(少用)<many-to-one><one-to-one>标签上,可以取值false,proxy,noproxy
当为true时,会有懒加载特性,当为false时会产生N+1问题,比如一个学生对应一个班级,用一条SQL查出10个学生,当访问学生的班级属性时Hibernate会再产生10条SQL分别查出每个学生对应的班级.
(不用)<class>标签上,可以取值true,false
默认为true,当为false时,load()方法将失去懒加载的特性与get()一样,不影响集合(<set><list>)标签上的lazy特性
(不用)<property>标签上,可以取值true,false
默认值为false,懒加载某个字段,无意义,不要使用

----------------------------------------------------------
get()与load()的区别
get()无懒加载特性,马上执行SQL查询.
load()有懒加载特性,会返加一个代理对象,所以永远不为null,先不执行SQL,要取对象的值时才执行SQL语句,前题session不能关闭,<class>标签上lazy不为false.

----------------------------------------------------------
实现懒加载的前提:1 PO不能是final的
2 能实现懒加载的对象(PO)都是被CGLIB改写的代理对象,所以不能是final修饰的
3 须要asm,cglib两个jar包
4 相应的lazy属性为true
5 相应的fetch属性为select
----------------------------------------------------------
什么时候出遇到懒加载
1 使用load()
2 一对一<one-to-one>
查主对象 默认使用join连接,不会发生懒加载
查从对象 默认会发生懒加载,先执行一句select查出从对象,当通过从对象访问了主对象时,再执行一句select查出主对象.

3 多对一<many-to-one>
在使用hbm.xnl时,取多的一方时,默认会懒加载,不取一的一方
在使用JPA时,取多的一方时,默认自动使用join on语句取出一的一方(用户与组,用户是多的一方,组是一的一方)

4 一对多(<set><list>)
默认会懒加载,这是必须的,是重常用的。

----------------------------------------------------------
实现懒加载的方案:


方法一:(没有使用懒加载)
用 Hibernate.initialize(de.getEmps()) 提前加载一下.

方法二:
把与Session脱离的对象重新绑定
lock()方法是用来让应用程序把一个未修改的对象重新关联到新session的方法。

Java代码 复制代码 收藏代码
  1. //直接重新关联
  2. session.lock(fritz, LockMode.NONE);
  3. //进行版本检查后关联
  4. session.lock(izi, LockMode.READ);
  5. //使用SELECT ... FOR UPDATE进行版本检查后关联
  6. session.lock(pk, LockMode.UPGRADE);
  1. //直接重新关联
  2. session.lock(fritz, LockMode.NONE);
  3. //进行版本检查后关联
  4. session.lock(izi, LockMode.READ);
  5. //使用SELECT ... FOR UPDATE进行版本检查后关联
  6. session.lock(pk, LockMode.UPGRADE);
//直接重新关联
session.lock(fritz, LockMode.NONE);
//进行版本检查后关联
session.lock(izi, LockMode.READ);
//使用SELECT ... FOR UPDATE进行版本检查后关联
session.lock(pk, LockMode.UPGRADE);




方法三:
OpenSessionInView

OpenSessionInViewFilter是Spring提供的一个针对Hibernate的一个支持类,其主要意思是在发起一个页面请求时打开Hibernate的Session,一直保持这个Session,直到这个请求结束,具体是通过一个Filter来实现的。

由于Hibernate引入了Lazy Load特性,使得脱离Hibernate的Session周期的对象如果再想通过getter方法取到其关联对象的值,Hibernate会抛出一个LazyLoad的Exception。所以为了解决这个问题,Spring引入了这个Filter,使得Hibernate的Session的生命周期变长。

首先分析一下它的源码,可以发现,它所实现的功能其实比较简单:

Java代码 复制代码 收藏代码
  1. SessionFactory sessionFactory = lookupSessionFactory(request);
  2. Session session = null;
  3. boolean participate = false;
  4. if (isSingleSession()) {
  5. // single session mode
  6. if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
  7. // Do not modify the Session: just set the participate flag.
  8. participate = true;
  9. } else {
  10. logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
  11. session = getSession(sessionFactory);
  12. TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
  13. }
  14. } else {
  15. // deferred close mode
  16. if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
  17. // Do not modify deferred close: just set the participate flag.
  18. participate = true;
  19. } else {
  20. SessionFactoryUtils.initDeferredClose(sessionFactory);
  21. }
  22. }
  23. try {
  24. filterChain.doFilter(request, response);
  25. } finally {
  26. if (!participate) {
  27. if (isSingleSession()) {
  28. // single session mode
  29. TransactionSynchronizationManager.unbindResource(sessionFactory);
  30. logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
  31. closeSession(session, sessionFactory);
  32. }else {
  33. // deferred close mode
  34. SessionFactoryUtils.processDeferredClose(sessionFactory);
  35. }
  36. }
  37. }
  1. SessionFactory sessionFactory = lookupSessionFactory(request);
  2. Session session = null;
  3. boolean participate = false;
  4. if (isSingleSession()) {
  5. // single session mode
  6. if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
  7. // Do not modify the Session: just set the participate flag.
  8. participate = true;
  9. } else {
  10. logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
  11. session = getSession(sessionFactory);
  12. TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
  13. }
  14. } else {
  15. // deferred close mode
  16. if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
  17. // Do not modify deferred close: just set the participate flag.
  18. participate = true;
  19. } else {
  20. SessionFactoryUtils.initDeferredClose(sessionFactory);
  21. }
  22. }
  23. try {
  24. filterChain.doFilter(request, response);
  25. } finally {
  26. if (!participate) {
  27. if (isSingleSession()) {
  28. // single session mode
  29. TransactionSynchronizationManager.unbindResource(sessionFactory);
  30. logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
  31. closeSession(session, sessionFactory);
  32. }else {
  33. // deferred close mode
  34. SessionFactoryUtils.processDeferredClose(sessionFactory);
  35. }
  36. }
  37. }
SessionFactory sessionFactory = lookupSessionFactory(request);
Session session = null;
boolean participate = false;

if (isSingleSession()) {
	// single session mode
	if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
	// Do not modify the Session: just set the participate flag.
	participate = true;
       }	else {
	logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter");
	session = getSession(sessionFactory);
	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	}
} else {
	// deferred close mode
	if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) {
// Do not modify deferred close: just set the participate flag.
	participate = true;
    } else {
	SessionFactoryUtils.initDeferredClose(sessionFactory);
    }
}

try {
	filterChain.doFilter(request, response);
} finally {
	if (!participate) {
           	if (isSingleSession()) {
	         	// single session mode
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter");
		closeSession(session, sessionFactory);
	}else {
		// deferred close mode
		SessionFactoryUtils.processDeferredClose(sessionFactory);
	}
}
}


在上述代码中,首先获得SessionFactory,然后通过SessionFactory获得一个Session。然后执行真正的Action代码,最后根据情况将Hibernate的Session进行关闭。整个思路比较清晰。

注意,在这里有个2个Tips:
1)通过getSession()获得的这个Session做了一次
session.setFlushMode(FlushMode.NEVER); 有关FlushMode可以参考一下这篇文章。http://www2.matrix.org.cn/resource/article/2006-10-08/Hibernate+FlushMode+NEVER_312bca85-5699-11db-91a0-d98dff0aec60.html
2)Spring对拿到的Session做了一次绑定到当前线程的做法,使得这个Session是线程安全的。

从上述代码其实可以得到一些对我们的开发有帮助的结论:
1)如果使用了OpenSessionInView模式,那么Spring会帮助你管理Session的开和关,从而你在你的DAO中通过HibernateDaoSupport拿到的getSession()方法,都是绑定到当前线程的线程安全的Session,即拿即用,最后会由Filter统一关闭。
2)由于拿到的Hibernate的Session被设置了session.setFlushMode(FlushMode.NEVER); 所以,除非你直接调用session.flush(),否则Hibernate session无论何时也不会flush任何的状态变化到数据库。因此,数据库事务的配置非常重要。(我们知道,在调用org.hibernate.Transaction.commit()的时候会触发session.flush())我曾经见过很多人在使用OpenSessionInView模式时,都因为没有正确配置事务,导致了底层会抛出有关FlushMode.NEVER的异常。

OpenSessionInView这个模式使用比较简单,也成为了大家在Web开发中经常使用的方法,不过它有时候会带来一些意想不到的问题,这也是在开发中需要注意的。
1. 在Struts+Spring+Hibernate环境中,由于配置的问题导致的模式失效
这个问题以前论坛曾经讨论过,可以参考一下下面这个帖子:
http://www.javaeye.com/topic/15057

2. OpenSessionInView的效率问题
这个问题也有人在论坛提出过,Robbin曾经做过具体的测试,可以具体参考一下下面这个帖子:
http://www.javaeye.com/topic/17501

3. 由于使用了OpenSessionInView模式后造成了内存和数据库连接问题
这个问题是我在生产环境中碰到的一个问题。由于使用了OpenSessionInView模式,Session的生命周期变得非常长。虽然解决了Lazy Load的问题,但是带来的问题就是Hibernate的一级缓存,也就是Session级别的缓存的生命周期会变得非常长,那么如果你在你的Service层做大批量的数据操作时,其实这些数据会在缓存中保留一份,这是非常耗费内存的。还有一个数据库连接的问题,存在的原因在于由于数据库的Connection是和Session绑在一起的,所以,Connection也会得不到及时的释放。因而当系统出现业务非常繁忙,而计算量又非常大的时候,往往数据连接池的连接数会不够。这个问题我至今非常头痛,因为有很多客户对数据连接池的数量会有限制,不会给你无限制的增加下去。

4. 使用了OpenSessionInView模式以后取数据的事务问题
在使用了OpenSessionInView以后,其实事务的生命周期比Session的生命周期来得短,就以为着,其实有相当一部分的查询是不被纳入到事务的范围内的,此时是否会读到脏数据?这个问题我至今不敢确认,有经验的朋友请指教一下。

最后提一下OpenSessionInView模式的一些替代方案,可以使用OpenSessionInViewInterceptor来代替这个Filter,此时可以使用Spring的AOP配置,将这个Interceptor配置到你所需要的层次上去。另外就是只能使用最古老的Hibernate.initialize()方法进行初始化了。

http://elf8848.javaeye.com/blog/666251懒加载

http://www.javaeye.com/topic/32001 (OpenSessionInView)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值