How to override Spring Batch CompositeItemWriter manage transaction for delegate writers in case of exception arises?

后端 未结 3 479
醉梦人生
醉梦人生 2020-12-17 02:53

I am extending this How does Spring Batch CompositeItemWriter manage transaction for delegate writers? question here:

In my case I\'ve a below CompositeItemWrit

3条回答
  •  再見小時候
    2020-12-17 03:32

    A couple things here:

    1. Do not use @Transactional with Spring Batch - Spring Batch manages the transactions for you so using that annotation will cause issues. Do not use it.
    2. Manage the exceptions yourself - In the scenario you are describing, where you want to call four ItemWriter implementations for the same item, but want to skip the exceptions at the delegated ItemWriter level, you will need to write your own CompositeItemWriter implementation. Spring Batch provides that level of composition (where we delegate to each ItemWriter implementation with the same item) out of convenience, but from the framework's perspective it is just a single ItemWriter. In order to handle exceptions at the child ItemWriter level, you will need to write your own wrapper and manage the exceptions yourself.

    UPDATE:
    An example implementation of the custom ItemWriter I'm referring to (note the code below is untested):

    public class MyCompositeItemWriter implements ItemWriter {
          private List> delegates;
     
        @Override
          public void write(List items) throws Exception {
                for(ItemWriter delegate : delegates) {
                   try {
                      delegate.write(items);
                   }
                   catch (Exception e) {
                      // Do logging/error handling here
                   }
                }
        }
    
        @Override
        public void setDelegates(List> delegates) {
            super.setDelegates(delegates);
            this.delegates = delegates;
        }
    }
    

提交回复
热议问题