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

Hibernate : CurreantSession

 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello:

I consulted Hibernate reference manual and some documentation on the web, and I confused about the currentSession and session-pre-request pattern.

I have few questions:

1- Is it a must to begin a transaction for every database access - including just reading?

2- If the answer to the above question is yes, how should I end the transaction for read operations? should I use tx.commit()?

3- If I call sessionFactory.getCurrentSession() do I need to close the session, or it is closed automatically?

Her is how my method looks like:

try
{
hbnSession = sessionFactory.getCurrentSession();
hbnSession.beginTransaction();
user = (User)hbnSession.get(User.class, userId);
}
catch(Exception e)
{
throw(e);
}
finally
{
if(hbnSession != null)
hbnSession.close();
}


In the examples provide in the Hibernate documentations they don't close the session.

Thank you
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you should be in the habit of beginning the transaction and commit, even for read. Why?

1. consistency
2. In most environments you will get an exception if you do not begin a transaction.
3. Later on you Use case might change where it does need to do CUD operations and would need the transaction.


In currentSession, yes It will close the session for you, but you can still call close and be ok.

Hanna, it looks like you are doing a really good job in learning Hibernate. I can also highly, highly recommend the "Java Persistence with Hibernate" book from Manning Publishers. It is the only book out there that covers ever single detail about Hibernate, and does a very good job explaining everything. But it is a big book.

Good Luck

Mark
Mark
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mark. I have been using Hibernate reference manaul and reading the documentation in Hibernate site. It is very helpfull materials. I am going to get the book.
Again, thank you for sharing your knowledge.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic