JpaItemWriter: no transaction is in progress

后端 未结 2 632
鱼传尺愫
鱼传尺愫 2020-12-11 06:11

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 (\'         


        
相关标签:
2条回答
  • 2020-12-11 06:16

    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();
        }
    
    0 讨论(0)
  • 2020-12-11 06:23

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题