Hibernate Session Management

As the name suggest, we look at how the session management in hibernate is controlled.
session management includes creating the session, performing transactions with session and closing the session

There are 2 ways this can be managed.
1) By User
2) By Hibernate container

By User:


getOpenSession()- Creates a new session on every call. The session management will be totally managed by the user (creation/closing).

getStatelessSession()- Creates a new session on every call. Does not have an Hibernate capabilities like caching, dirty checking.. 


By Hibernate Container:


Is the above scenario, a new session object is created every time. But, there can be some scenarios where your application does not demand to create a new session every time which is time consuming. Instead, re-using  the existing  session can also suffice. For this, we need to define the context and the scope of the session.


Since, Hibernate session can be obtained from the SessionFactory class. we can wire the session management property to the SessionFactory bean to control the session creation with the help of Hibernate Container and the session can be accessed by calling getCurrentSession() on SessionFactory.

Below are the 3 default implementations provided by the Hibernate  for this SessionContext behavior

<prop key="hibernate.current_session_context_class">XXXXXX</prop>
VALUES - thread/jta/managed

1.    Thread – Session bound to the thread. 
 eg: In single thread, there will be 1 thread. So, only 1 session will be reused by calling getCurrentSession()

2.    Jta – session bound to the transaction. (Used only with App Server)
3.    Managed- Managing sessions is deferred for customization.

This implementation was released in 3.1 version. With this evolution, Spring's HibernateTemplate was made obsolete. With this way, we de-couple Spring from Hibernate.

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)