title: Spring Batch Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Transaction already active
body: <p>My Spring Batch job is started every 5 minutes - basically it reads a string, uses the string as a parameter in a sql query, and prints out the resulting sql result list.   Mostly it seems to be running ok, but I notice sporadic errors in my logs every 5-10 runs</p>
  
  <pre><code>2017-05-05 11:13:26.101  INFO 9572 --- [nio-8081-exec-8] c.u.r.s.AgentCollectorServiceImpl    : Could not open JPA E
  ntityManager for transaction; nested exception is java.lang.IllegalStateException: Transaction already active
  </code></pre>
  
  <p>My job is started like from my AgentCollectorServiceImpl class</p>
  
  <pre><code>@Override
  public void addReportIds(List&lt;Integer&gt; reportIds) {
      try {
              .toJobParameters();
          jobLauncher.run(job, jobParameters);
      } catch (Exception e) {
          log.info(e.getMessage());
      }
  }
  </code></pre>
  
  <p>My BatchConfig class looks like</p>
  
  <pre><code>@Configuration
  @EnableBatchProcessing
  @Import(AppConfig.class)
  public class BatchConfig {
  
      @Autowired
      private JobBuilderFactory jobBuilderFactory;
  
      @Autowired
      private StepBuilderFactory stepBuilderFactory;
  
      @Autowired
      private AppConfig appConfig;
  
      @Bean
      public Reader reader() {
          return new Reader();
      }
  
      @Bean
      public Processor processor() {
          return new Processor();
      }
  
      @Bean
      public Writer writer() {
          return new Writer();
      }
  
      @Bean
      public Job job() {
          return jobBuilderFactory.get("job")
              .incrementer(new RunIdIncrementer())
              .flow(step1())
              .end()
              .build();
      }
  
      @Bean
      public Step step1() {
          return stepBuilderFactory.get("step1")
              .&lt;String, String&gt; chunk(1)
              .reader(reader())
              .processor(processor())
              .writer(writer())
              .build();
      }
  }
  </code></pre>
  
  <p>My AppConfig class looks like</p>
  
  <pre><code>@Configuration
  @PropertySource("classpath:application.properties")
  @ComponentScan
  public class AppConfig {
  
  
      @Bean
      public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
          LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
          em.setDataSource(organizationDataSource());
          em.setPackagesToScan(new String[]{"com.organization.agentcollector.model"});
          JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
          em.setJpaVendorAdapter(vendorAdapter);
          em.setJpaProperties(additionalProperties());
  
          return em;
      }
  
      Properties additionalProperties() {
          Properties properties = new Properties();
          properties.setProperty("hibernate.dialect", "com.organization.agentcollector.config.SQLServerDialectOverrider");
          return properties;
      }
      @Bean
      JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
          return transactionManager;
      }
  </code></pre>
  
  <p>My Processor class looks like</p>
  
  <pre><code>public class Processor implements ItemProcessor&lt;String, String&gt; {
  
      private final Logger log = LoggerFactory.getLogger(Processor.class);
  
      @Autowired
      EventReportsDAOImpl eventReportsDAOImpl;
  
      @Override
      public String process(String reportIdsJson) throws Exception {
  
          String eventReportsJson = eventReportsDAOImpl.listEventReportsInJsonRequest(reportIdsJson);
          //System.out.println(returnContent+"PROCESSOR");
          return eventReportsJson;
      }
  
  }
  </code></pre>
  
  <p>My DAOImpl class looks like</p>
  
  <pre><code>@Component
  @Transactional
  public class EventReportsDAOImpl implements EventReportsDAO {
  
      @PersistenceContext
      private EntityManager em;
  
      @Override
      public EventReports getEventReports(Integer reportId) {
          return null;
      }
  
      @Override
      public String listEventReportsInJsonRequest(String reportIds) {
  
          System.out.println("Event Report reportIds processing");
          ArrayList&lt;EventReports&gt; erArr = new ArrayList&lt;EventReports&gt;();
          String reportIdsList = reportIds.substring(1, reportIds.length() - 1);
          //System.out.println(reportIdsList);
  
          try {
              StoredProcedureQuery q = em.createStoredProcedureQuery("sp_get_event_reports", "eventReportsResult");
              q.registerStoredProcedureParameter("reportIds", String.class, ParameterMode.IN);
              q.setParameter("reportIds", reportIdsList);
              boolean isResultSet = q.execute();  
              erArr = (ArrayList&lt;EventReports&gt;) q.getResultList();
          } catch (Exception e) {
              System.out.println("No event reports found for list " + reportIdsList);
          }
  
          return erArr.toString();
      }
  </code></pre>
  
  <p>I thought Spring would manage transactions automatically.  The error seems to suggest that a transaction is not being properly closed?  </p>
  
  <p>One thing I tried was removing all @Transactional annotations from my code as I read that @EnableBatchProcessing already injects a Transaction Manager into each step - but when I did this, I saw the 'transaction already active' error much more frequently.</p>
  
  <p>Any advice appreciated on how to fix this, thank you!</p>