title: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException
body: <p>I am quite new to Spring and Spring-Batch in particular. 
  Still I somehow managed to install the <strong>Spring Batch-Admin</strong>. I added custom jobs and <strong>Hibernate/JPA</strong> for persistence. </p>
  
  <p>Everything is working as expected, up to the point where the first chunk should be persisted. Then I receive the following error-message:</p>
  
  <pre><code>org.springframework.transaction.CannotCreateTransactionException: 
        Could not open JPA  EntityManager for transaction;
  
  nested exception is java.lang.IllegalStateException: Already value
        [org.springframework.jdbc.datasource.ConnectionHolder@60d31437] 
        for key [org.springframework.jdbc.datasource.DriverManagerDataSource@12da4b19] 
        bound to thread [jobLauncherTaskExecutor-1]
  </code></pre>
  
  <p>This is the <strong>full stacktrace</strong>:</p>
  
  <pre><code>org.springframework.transaction.CannotCreateTransactionException: Could not open JPA  EntityManager for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder@43f9e588] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@84f171a] bound to thread [jobLauncherTaskExecutor-1]
       at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
       at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
       at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
       at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
       at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
       at com.sun.proxy.$Proxy41.saveIfUnique(Unknown Source)
       at com.qompa.batch.ArticleItemWriter.write(ArticleItemWriter.java:28)
       at org.springframework.batch.core.step.item.SimpleChunkProcessor.writeItems(SimpleChunkProcessor.java:171)
       at org.springframework.batch.core.step.item.SimpleChunkProcessor.doWrite(SimpleChunkProcessor.java:150)
       at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor$3.doWithRetry(FaultTolerantChunkProcessor.java:313)
       at org.springframework.batch.retry.support.RetryTemplate.doExecute(RetryTemplate.java:240)
       at org.springframework.batch.retry.support.RetryTemplate.execute(RetryTemplate.java:187)
       at org.springframework.batch.core.step.item.BatchRetryTemplate.execute(BatchRetryTemplate.java:213)
       at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor.write(FaultTolerantChunkProcessor.java:402)
       at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:194)
       at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:74)
       at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:386)
       at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
       at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:264)
       at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:76)
       at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
       at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
       at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
       at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:250)
       at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
       at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
       at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
       at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
       at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
       at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
       at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
       at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
       at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
       at java.lang.Thread.run(Thread.java:724)
  Caused by: java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder@43f9e588] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@84f171a] bound to thread [jobLauncherTaskExecutor-1]
       at org.springframework.transaction.support.TransactionSynchronizationManager.bindResource(TransactionSynchronizationManager.java:189)
       at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:402)
  ... 36 more
  </code></pre>
  
  <p>The same Job executes fine in a standalone application. The problem occurs only in the  Spring-Batch-Admin environment. Below you can see the <strong>project structure and dependencies</strong>:</p>
  
  <p><img src="https://i.stack.imgur.com/2vces.png" alt="enter image description here"></p>
  
  <p>This is the app-context.xml that overrides/extends the Batch-Admin configuration:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:task="http://www.springframework.org/schema/task" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
          http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"&gt;
  
      &lt;context:component-scan base-package="com.company.batch" /&gt;
  
      &lt;context:property-placeholder location="classpath:batch.properties" /&gt;
  
      &lt;import resource="classpath:/META-INF/spring/batch/jobs/article-job.xml" /&gt;
  
      &lt;bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
          &lt;property name="driverClassName" value="${batch.jdbc.driver}" /&gt;
          &lt;property name="url" value="${batch.jdbc.url}" /&gt;
          &lt;property name="username" value="${batch.jdbc.user}" /&gt;
          &lt;property name="password" value="${batch.jdbc.password}" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&gt;
          &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="packagesToScan" value="com.qompa.batch" /&gt;
          &lt;property name="jpaVendorAdapter"&gt;
              &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt;
                  &lt;property name="database" value="POSTGRESQL"&gt;&lt;/property&gt;
                  &lt;property name="showSql" value="true" /&gt;
                  &lt;property name="generateDdl" value="false" /&gt;
                  &lt;property name="databasePlatform" value="com.company.utils.persistence.CustomPGDialect" /&gt;
              &lt;/bean&gt;
          &lt;/property&gt;
          &lt;property name="jpaProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.hbm2ddl.auto"&gt;&lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
          &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt;
      &lt;/bean&gt;
      &lt;tx:annotation-driven transaction-manager="txManager" /&gt;
  
      &lt;!-- schedule tasks --&gt;
      &lt;task:scheduled-tasks&gt;
          &lt;task:scheduled ref="articleRetrieval" method="run"
              cron="0 0 */4 * * *" /&gt;
          &lt;task:scheduled ref="articleConversion" method="run"
              cron="0 15 */4 * * *" /&gt;
      &lt;/task:scheduled-tasks&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p>What I understand so far is that it has to do with the <a href="http://docs.spring.io/spring/docs/3.2.6.RELEASE/javadoc-api/org/springframework/scheduling/backportconcurrent/ThreadPoolTaskExecutor.html">ThreadPoolTaskExecutor</a> to which the <code>jobLauncherTaskExecutor</code> bean refers. It seems to handle <strong>connection pooling for concurrently running jobs</strong> ... but to be honest I have no clue how to change my configurations to make these things work.</p>
  
  <p>[Edit]: I am not even sure wether it is the afromentioned ThreadPoolTaskExecutor. But it seem s to be an implementation of the <a href="http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/core/task/TaskExecutor.html">TaskExecutor</a> interface.</p>
  
  <p>If anyone ran into a similar issue, or has a suggestion how to configure my application in a way that transactions can be created for my persistence methods: Please give me a hint!</p>