A Session
is also known as an interface that is used to get a physical connectivity with a database. It is instantiated every time we need to interact with the database for the CRUD (Create, Read, Update, Delete) operations. Persistent objects always travel from the application to the database and vice versa only through the Session
.
Now, let's find out more about Session
and how to open a new Session
using a SessionFactory
.
Before we create a Session
object, we need to get an object such as a SessionFactory
as a prerequisite:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Now, we will open a new Session
with the database:
Session session = sessionFactory.openSession();
Other methods are also available to open a Session
, as shown in the following code:
Session openSession(org.hibernate.Interceptor interceptor); Session openSession(java.sql.Connection connection, org.hibernate.Interceptor interceptor);
This will open a brand new Session
for us. It opens the database connection when it is created and holds it until the session is closed. A Session
created using these methods is not associated with any thread, so it's our responsibility to flush or close it once we are done with the database operation.
A Session
is a bridge between the Java application and hibernate. The Session
interface wraps the JDBC connection. A Session
always tries to be in sync with the persistent store where all transactions are made.
A Session
is always a part of first-level cache; it caches all the objects that are transmitted through that particular session. All cached objects will be destroyed once this session is closed.
We can use the same session instead of creating a brand-new session; hibernate provides the facility to reuse an already created session.
Let's look at how to do it:
sessionFactory
:SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.getCurrentSession();
It may seem easy to get the current session, but the twist here is that you have to provide more configuration to the Configuration
object if you plan to reuse the Session
, as shown in the following code:
<property name="hibernate.current_session_context_class"> Thread </property>
In the preceding code, we set a thread
value for the hibernate.current_session_context_class
key, meaning that the context of the current Session
is limited to the life of the current thread only.
For example, in a non-multithreaded environment, a Session
is created when the main thread is started. It will close automatically once the SessionFactory
is closed.