I\'d like to use JpaItemWriter to batch persist entities. But when I use the following code to persist, I\'m told:
Hibernate:
select
nextval (\'
I agree with Michael Minella: Spring batch job repository does not like to share its transaction manager with others. The logic is simple, if you share your job transaction manager with your step transaction manager upon step failure it will rollback both the step and the data written to the job repository. This means that you will not persist data for job restart. In order to use two transaction managers you need to:
Delete @EnableTransactionManagement in case you use it only for the @Transactional above
Define an additional transaction manager
@Bean
@Qualifier("jpaTrx")
public PlatformTransactionManager jpaTransactionManager() {
return new JpaTransactionManager(emf());
}
Set the transaction manager to your step
@Autowired
@Qualifier("jpaTrx")
PlatformTransactionManager jpaTransactionManager
//Reader is a FlatFileItemReader, writer is CustomItemWriter.
@Bean
public Step step(StepBuilderFactory steps,
MultiResourceItemReader<T> rea,
ItemProcessor<T, T> pro,
ItemWriter<T> wr) {
return steps.get("step")
//attach tx manager
.transactionManager(jpaTransactionManager)
.reader(rea)
.processor(proc)
.writer(wr)
.build();
}
I solved it creating my own transactional JpaWriter:
@Component
public class CustomItemWriter<T> extends JpaItemWriter<T> {
@Override
@Transactional
public void write(List<? extends T> items) {
super.write(items);
}
}