How to access hibernate session in Thread?

Since Hibernate sessions are not thread safe, I cannot get a hibernate currnet session through sessionFactory.getCurrentSession ();

If I choose sessionFactory.openSession (); it works fine for the thread itself, but for nested classes [called from the thread] it will not allow me to access the same newly opened session [Throws "No Session found for current thread" exception].

I am using Spring 3.1.1 and Hibernate 4.1.3

Is there a way to get the current session in a thread?

Or is there a way to access a newly opened session on nested classes called from a thread?

+4
source share
1 answer

When you use Spring and hibernate, you will get the current session using sessionFactory.getCurrentSession(); if you use it in a transaction. Otherwise, you will get an exception with the message: No Session found for current thread .

eg.

 void someDBOperation() { Session session = sessionFactory.getCurrentSession(); // if not in transaction, exception : No Session found for current thread // some code } 


 @Transactional // use either annotated approach or xml approach for transaction void someDBOperation() { Session session = sessionFactory.getCurrentSession(); // you will get session here // some code } 
+1
source

Source: https://habr.com/ru/post/1441968/


All Articles