Preventing connection leaks when accessing Session directly in DAO methods

Guys, 

 
as discussed during the call this morning, when retrieving a reference to the Hibernate session directly in DAO methods, like this
 
Session session = this.getSession();
 
you will quickly run into problems with connection leaks if you do not close this session afterwards. However, if the method where you access the session is wrapped in a transaction, you'll get an exception saying that the transaction failed, because the session was closed. 
 
This can be fixed by adding the @Transactional configuration below to the DAO method as well. The Propagation.REQUIRED will force the getSession method to use any existing transaction that exists, or create a new one none exists. 
 
@Transactional(propagation = Propagation.REQUIRED)
 
This means that when calling the DAO method from a service method which is already wrapped in a transaction, the getSession() call will re-use the existing, open transaction, but if you call the DAO method outside any existing transaction a new one will be created only for that method call.
 
Should you experience any issues with this approach, let us know - but from the testing I've done so far this works well. 

转载于:https://www.cnblogs.com/defei/archive/2012/11/21/2780486.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值