Skip to content
Advertisement

HibernateException: Couldn’t obtain transaction-synchronized Session for current thread

I’m getting the following exception when trying to use my @Service annotated classes:

JavaScript

The way I initialize my application is complicated so I need to provide a link to the full base code to get additional information: https://github.com/dtrunk90/webapp-base. I’m using this as a maven overlay.

And here is the necessary code:

Initializer (from webapp-base):

JavaScript

Initializer (from my webapp):

JavaScript

@Configuration (from webapp-base):

JavaScript

@Configuration (from my webapp):

JavaScript

@Service:

JavaScript

@Repository:

JavaScript

Then I’m autowiring PageViewService and use its methods.

I know there are several questions with the same problem here but I already checked anything:

Could not obtain transaction-synchronized Session for current thread

  • @EnableTransactionManagement is provided
  • Services wil be autowired as interfaces

HibernateException: Could not obtain transaction-synchronized Session for current thread

  • Checked for @Transactional everywhere I use getSessionFactory().getCurrentSession()

Spring Hibernate – Could not obtain transaction-synchronized Session for current thread

  • @EnableTransactionManagement is provided
  • Checked for @Transactional everywhere I use getSessionFactory().getCurrentSession()

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

  • There’s no helpful answer. I want component scanning for all my components, not only controller

Advertisement

Answer

Looking at your log I can instantly tell that your transaction settings are wrongly set. That’s because there’s no TransactionInterceptor call in your stack trace.

The TransactionInterceptor is called by your Spring Service proxies when your web controllers call the actual Service methods.

  1. Make sure you use the Spring hibernate4 classes:

    JavaScript
  2. Don’t override @Transactional methods, but use a template patterns instead.

  3. Try using JPATransactionManager instead so you can inject the current EntityManager with the @PersistenceContext annotation instead. This is much more elegant than calling sessionFactory.getCurrentSession() in every DAO method.

Advertisement