Tejash
Tejash

Reputation: 41

How to access hibernate session in Thread?

As Hibernate sessions are not thread-safe, I am not able to get currnet hibernate session through sessionFactory.getCurrentSession();

If I choose sessionFactory.openSession(); it works fine for thread itself but for nested classes[called from the thread] it wont allow me to access 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 any way to get the current session in thread?

Or is there any way to access newly opened session to nested classes which are called from the thread?

Upvotes: 4

Views: 1681

Answers (1)

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

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

e.g. :

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
}

Upvotes: 1

Related Questions