Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubts in clossing session

 
balaji anatha padmanaban
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

In my code in every method session is created by calling
Session session = HibernateUtil.getCurrentSession();
inside this method it is calling

Session s = null;
try{
s = sessionFactory.getCurrentSession();
}catch (Exception e){}

So i get session and doing some transaction and at last transaction is commited by calling commit method but session is not closed .
My questions are
So I need to close the session in every method?
If not either it will reflect in database telling that session are open?
So, please clear my doubts how to handle the session properly and most effeciently.

Thanks
waiting for the reply.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So I need to close the session in every method?

That depends. The recommendation is to keep Sessions short. This reduces the likelyhood of stale data. But your methods may form part of a larger transaction (i.e. one business method calls n DAO methods) in this case you probably would benefit from keeping the session open till the business operation completes.


If not either it will reflect in database telling that session are open?

Not sure what you mean here. A Session doesn't necessarily equate to a connection.

Have a read through the Hibernate web site for possible Session handling patterns. There are a few, for example open session in view and this about session and transaction demarcation.
 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

Remember that calling session.close() ends the session by releasing the JDBC connection (and cleans up after itself), so it's not something you want to do if you haven't finished a 'unit of work'.

A common pattern is the session-per-request implementation pattern, but I strongly recommend reading the Hibernate article below as it discusses many patterns in relation to Hiberante:

Hibernate page on Sessions and Transactions

Hope that helps!

*Sorry Paul, I didn't see your post earlier, mine probably wasn't needed *
[ September 11, 2008: Message edited by: Martijn Verburg ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic