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. 
posted @ 2012-11-21 12:11  德飞  阅读(125)  评论(0编辑  收藏  举报