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
<session-factory> <!-- Put other elements here --> <property name="hibernate.current_session_context_class"> thread </property> </session-factory>