问题描述
我想从文件中读取项目并将其插入表中。为此,我正在使用FlatFileItemReader
和JdbcBatchItemWriter
。我在该步骤中使用块定向。所以我的步骤将如下所示。
private Step createPoliciesstep() {
return stepBuilderFactory.get("CreatePoliciesstep")
.<PolicyDTO,PolicyDTO>chunk(2)
.reader(createPoliciesReaderFunc())
.writer(createPoliciesWriterFunc())
.listener(createPoliciesWriteListener)
.listener(createPoliciesstepListener)
.build();
}
我给的commit-interval是2。所以每2条记录都会发生一次提交。例如,在读取第4条记录时,抛出了一些异常。当时没有插入第3和第4条记录,这绝对可以。我想回退表上的第一条记录和第二条记录(在先前的事务中提交)。
我期望的是在交易
Begin
之前。在执行步骤之后,应commit
进行交易。在这之间,任何异常都应回滚整个步骤。
我尝试通过添加DataSourceTransactionManager
的事务管理器和事务属性来解决问题,但是没有用。添加完我的步骤后,像这样
@Bean
PlatformTransactionManager policyTransactionManager(@Qualifier("MysqLDataSource")DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
private Step createPoliciesstep() {
log.info("Create Policies Step Initiated ");
DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
attribute.setPropagationBehavior(Propagation.required.value());
attribute.setIsolationLevel(Isolation.DEFAULT.value());
return stepBuilderFactory.get("CreatePoliciesstep")
.transactionManager(policyTransactionManager)
.<PolicyDTO,PolicyDTO>chunk(2)
.reader(createPoliciesReaderFunc())
.writer(createPoliciesWriterFunc())
.listener(createPoliciesWriteListener)
.transactionAttribute(attribute)
.listener(createPoliciesstepListener)
.build();
}
谁能建议一些好的方法来回滚整个步骤。提前谢谢!!!
解决方法
Spring Batch中的事务边界是围绕块而不是步骤定义的。因此,不可能为整个步骤配置事务。
您的用例的常见模式是添加一个单独的步骤,该步骤根据上一步的退出状态(成功或失败)执行“补偿操作”,以回退上一步的更改。您的情况。