Session from the Hibernate SessionFactory: openSession() and getCurrentSession().The openSession() method always creates and returns a new Session instance each time it is called. In contrast, the getCurrentSession() method returns the Session associated with the current context (such as the current thread or transaction). If no Session is available in the current context, Hibernate creates a new one and associates it with that context.
Let's explore a few more differences between openSession() and getCurrentSession().
openSession():-
The
openSession()method creates a newSessioninstance every time it is called.You must explicitly flush and close the
Sessionafter use.In a single-threaded environment,
openSession()is generally less efficient thangetCurrentSession()because it creates a newSessionfor every call.No additional Hibernate configuration is required to use the
openSession()method.
getCurrentSession():-
The
getCurrentSession()method returns theSessionassociated with the current Hibernate context. If noSessionexists in the current context, Hibernate creates a new one and binds it to that context.You do not need to explicitly flush or close the
Session. When using transaction management, Hibernate automatically manages the session lifecycle.In a single-threaded environment,
getCurrentSession()is generally more efficient thanopenSession()because it reuses the context-boundSessioninstead of creating a new one for every request.To use
getCurrentSession(), you must configure thehibernate.current_session_context_classproperty (or use a framework such as Spring, which manages the current session automatically). Otherwise, callinggetCurrentSession()may result in aHibernateException.