'No CurrentSessionContext configured, while using getCurrentSession()
I am changing my code from openSession() to getCurrentSession() so it won't create connections at each request.
I have done code in class as:
public Session openSession(boolean current1){
int count = 0;
int MAX_COUNT = 10;
// this.printIdMap();
while( count++ < MAX_COUNT) {
try {
this.session = this.getSessionFactory().getCurrentSession();
this.transaction = this.session.beginTransaction();
this.IncDecCounter(true);
// this.session.getTransaction().commit();
break;
}
catch ( Exception e ) {
this.printIdMap();
e.printStackTrace();
try { this.session.close(); } catch( Exception e1 ) {}
}
}
return this.session;
}
I have checked in multiple places to set property in hibernate.cfg.xml file.
<property name="hibernate.current_session_context_class">thread</property>
I also tried
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
but facing error as
org.hibernate.HibernateException: No CurrentSessionContext configured!
The hibernate version which I am using is 5.4.1
Solution 1:[1]
Lets imagine your Hibernate session manager class looks like this
public class HibernateSessionManager {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties());
return configuration.buildSessionFactory(serviceRegistryBuilder
.buildServiceRegistry());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Use this property in your configuration file
<property name="hibernate.current_session_context_class">thread</property>
Instead of you currecnt one i.e
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocal??SessionContext</property>
And get your session with
Session session = HibernateSessionManager.getSessionFactory().openSession();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
