Spring Batch无法打开JPA EntityManager进行事务处理;嵌套异常是java.lang.IllegalStateException:事务已处于活动状态

时间:2017-05-05 16:40:03

标签: java spring jpa spring-data spring-batch

My Spring Batch作业每5分钟启动一次 - 基本上它读取一个字符串,在sql查询中使用该字符串作为参数,并打印出生成的sql结果列表。大多数情况下,它似乎运行正常,但我发现每5-10次运行中我的日志中出现零星错误

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

我的工作是从我的AgentCollectorServiceImpl类开始的

@Override
public void addReportIds(List<Integer> reportIds) {
    try {
            .toJobParameters();
        jobLauncher.run(job, jobParameters);
    } catch (Exception e) {
        log.info(e.getMessage());
    }
}

我的BatchConfig类看起来像

@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")
            .<String, String> chunk(1)
            .reader(reader())
            .processor(processor())
            .writer(writer())
            .build();
    }
}

我的AppConfig类看起来像

@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;
    }

我的处理器类看起来像

public class Processor implements ItemProcessor<String, String> {

    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;
    }

}

我的DAOImpl类看起来像

@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<EventReports> erArr = new ArrayList<EventReports>();
        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<EventReports>) q.getResultList();
        } catch (Exception e) {
            System.out.println("No event reports found for list " + reportIdsList);
        }

        return erArr.toString();
    }

我认为Spring会自动管理交易。该错误似乎表明交易未正确关闭?

我尝试过的一件事是从我的代码中删除所有@Transactional注释,因为我读到@EnableBatchProcessing已经在每个步骤中注入了一个事务管理器 - 但是当我这样做时,我更频繁地看到'事务已经激活'错误。

任何有关如何解决这个问题的建议,谢谢!

1 个答案:

答案 0 :(得分:0)

@Transactional表示法建立了一个事务范围,它指示事务何时开始和结束,也称为其边界。如果您在此边界之外操作,您将收到错误。

首先,我发现这些文档对Spring事务最有帮助:http://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html具体this section

其次,您可能希望启用跟踪级别日志以及可能的SQL语句来帮助调试此问题。为此,我将以下内容添加到application.properties

spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.show-sql=true
logging.level.org.hibernate=TRACE

这里会有很多输出,但你会很清楚幕后发生的事情。

第三,我学习如何使用@Transactional时最重要的部分是每次调用DAO都会创建一个新会话 - 或者 - 如果在同一事务范围内,则重用现有会话。有关此示例,请参阅上面的文档。