Could Not Open JPA Entitymanager for Transaction (Using Localcontainerentitymanagerfactorybean)

Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException

The error comes from JpaTransactionManager line 403:

TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);

The error means that the transaction manager is trying to bind the datasource (not the entity manager) to the thread, but the datasource is already there and this is unexpected.

Note that the transaction manager had not started yet to bind the Entity Manager to the thread, that would happen next at JpaTransactionManager line 416:

There are two possible explanations:

  • Somebody (another transaction manager?) is adding the datasource to the thread before the transaction manager and this is unexpected.

  • Or no one is adding the datasource to the transaction manager, is just that at the end of the task execution no one cleans the thread before returning it to the pool, maybe due an error or an unhandled exception.

One question, does this also happen for only one execution thread, or only when there are several?

To find out what the problem is, these are some steps:

  • run with a minimal number of threads that cause the problem

  • put a breakpoint in TransactionSynchronizationManager.bindResource() to see who adds the connection to the thread. The breakpoint can be a conditional breakpoint with a condition on the thread name: "jobLauncherTaskExecutor-1".equals(Thread.currentThread().getName())

  • put also a breakpoint in TransactionSynchronizationManager.unbindResource(), to see if the datasource is unbound from the thread. when the breakpoints hit, scroll down the stacktrace and see which classes are causing this.

Could not open JPA EntityManager for transaction in spring

I had the same problem. The solution is to use default-autowire="byName" instead of "byType" in your xml configuration. If you have "byType" Spring automatically autowire also the property "jtaDataSource" in the LocalContainerEntityManagerFactoryBean with your definied datasource bean.



Related Topics



Leave a reply



Submit