openSession
: When you call SessionFactory.openSession
, it always creates a new Session
object and give it to you.
You need to explicitly flush and close these session objects.
As session objects are not thread safe, you need to create one session object per request in multi-threaded environment and one session per request in web applications too.
getCurrentSession
: When you call SessionFactory.getCurrentSession
, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.
When you call SessionFactory.getCurrentSession
, it creates a new Session
if it does not exist, otherwise use same session which is in current hibernate context. It automatically flushes and closes session when transaction ends, so you do not need to do it externally.
If you are using hibernate in single-threaded environment , you can use getCurrentSession
, as it is faster in performance as compared to creating a new session each time.
You need to add following property to hibernate.cfg.xml to use getCurrentSession
method:
<session-factory>
<!-- Put other elements here -->
<property name="hibernate.current_session_context_class">
thread
</property>
</session-factory>
openSession()
orclose()
. He only callsgetCurrentSession()
. I guess he setscurrent_session_context
tothread
. Now I think I understandgetCurrentSession()
. However, I don't know when should I useopenSession()
. – Scatterbrain