wood burning stoves*
The moose likes Object Relational Mapping and the fly likes Hibernate Exception and Session closing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate Exception and Session closing" Watch "Hibernate Exception and Session closing" New topic
Author

Hibernate Exception and Session closing

Zeki Karaca
Greenhorn

Joined: Oct 02, 2009
Posts: 20
Hi @ all

I am learning Hibernate and there are 2 things that are still confusing for me. Take a look at my example code:



Question 1.
I read a lot of tutorials on the internet and also about the differences between getCurrentSession() and openSession(). I know that if i use openSession i need to manage the sessions myself and should also flush/close it. I used getCurrentSession in my example so i did not add a finally clause to close the session used. Is this correct or should i still close the session myself?

Question 2.
Almost all example codes on the internet show a similar structure with a try/catch clause. But getCurrentSession also throws a HibernateException so why should i not put this in the try clause and catch an exception. I know it is a runtime exception but beginTransaction, save and commit also throw the same exception. Why do i catch these and not the one for getCurrentSession?

Please could someone help me to clarify these 2 questions? Thanks in advance.


SCJA | SCJP 6.0 | ...
Zeki Karaca
Greenhorn

Joined: Oct 02, 2009
Posts: 20
Please, is there anyone who can help me with these questions?
Zeki Karaca
Greenhorn

Joined: Oct 02, 2009
Posts: 20
One last attempt...
JayaSiji Gopal
Ranch Hand

Joined: Sep 27, 2004
Posts: 303
Here is the code that i get:


with currentSession(), you dont need to close it manually. All of that is automatically taken care for you.


SCJP 1.4, SCWCD 1.4<br /> <br />Thanks in advance!<br />Jayashree.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Hibernate Exception and Session closing