使用JSR-352的JobListener将记录插入数据库

时间:2016-02-05 10:54:31

标签: transactions listener spring-batch jsr352

我试图在JobListener实现的afterJob()方法中插入一些记录。我的听众看起来如下,

public class SampleListener2 implements JobListener {

    @Autowired
    DataSource dataSource;


    @Override
    public void beforeJob() throws Exception {}

    @Override
    public void afterJob() throws Exception {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        List<Object[]> objectList = new ArrayList<Object[]>();

        Object[] objectArray = {System.currentTimeMillis(), "After Job", "After Job", "1.0"};
        objectList.add(objectArray);

        jdbcTemplate.batchUpdate("insert into RAW_REPORT(DATE,IMPRESSIONS,CLICKS,EARNINGS) values (?,?, ?, ?)", objectList);

        System.out.println("After Job 2");


}

On Debugging我发现Spring-Batch没有提交事务,导致记录没有显示在DB中。如果我手动尝试提交事务,我可以通过DB

中的记录找到
public class SampleListener2 implements JobListener {

    @Autowired
    DataSource dataSource;

    @Inject
    private PlatformTransactionManager transactionManager;

    @Override
    public void beforeJob() throws Exception {}

    @Override
    public void afterJob() throws Exception {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

        List<Object[]> objectList = new ArrayList<Object[]>();

        Object[] objectArray = {System.currentTimeMillis(), "Before Job", "Before Job", "1.0"};
        objectList.add(objectArray);

        jdbcTemplate.batchUpdate("insert into RAW_REPORT(DATE,IMPRESSIONS,CLICKS,EARNINGS) values (?,?, ?, ?)", objectList);
        transactionManager.commit(status);
        System.out.println("Before Job 1");
    }

}

有人可以让我知道这种行为的细节,我宁愿不手动处理这些事务,并希望spring-batch在Listener中提交我的记录。请求您就此问题提供帮助

修改 用于测试场景的示例代码: https://github.com/rbutti/SpringBatch/tree/master/SpringJSR352

0 个答案:

没有答案