Hibernate requires a lot of configurations and sometimes you get weird exception and there is no clue that it’s because of some missing configuration.
org.hibernate.HibernateException: No CurrentSessionContext configured
I was working on a simple hibernate web application and getting below exception.
1 2 3 4 5 6 7 |
org.hibernate.HibernateException: No CurrentSessionContext configured! org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) com.journaldev.servlet.hibernate.GetEmployeeByID.doGet(GetEmployeeByID.java:31) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) |
When I looked at the source code, the statement that was throwing the exception was;
1 2 3 |
Session session = sessionFactory.getCurrentSession(); |
My Hibernate configuration was like this:
hibernate.cfg.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property> <!-- Mapping with model class containing annotations --> <mapping class="com.journaldev.servlet.hibernate.model.Employee"/> </session-factory> </hibernate-configuration> |
Fix for org.hibernate.HibernateException: No CurrentSessionContext configured
Everything looked fine to me and the exception didn’t clearly says what is missing.
After going through the SessionFactoryImpl
, I found that we also need to configure the current session context class to get the current session.
This is done in method buildCurrentSessionContext()
and it looks for property hibernate.current_session_context_class
.
From the method body, it became clear that the value of this property should be:
jta
for getting JTASessionContextmanaged
for ManagedSessionContextthread
for ThreadLocalSessionContext
The method also works if we provide above class name. So when I added this property in the hibernate configuration file, program started working fine.
Hibernate CurrentSessionContext class configuration example
Sample ways to define current_session_context_class property are:
1 2 3 |
<property name="hibernate.current_session_context_class">thread</property> |
Use below configuration if your hibernate configuration file is having xml format.
1 2 3 4 5 |
<property name="hibernate.current_session_context_class"> org.hibernate.context.internal.ThreadLocalSessionContext </property> |
Thats’s all for fixing org.hibernate.HibernateException: No CurrentSessionContext configured. I hope it will save you some time.