Search code examples
listspring-batchspring-jdbccompositeitemwriter

Writing List of Items using JdbcBatchItemWriter


Currently i am using JpaItemWriter to write the list of objects as below which is working fine. Now i want to change the JpaItemWriter to JdbcBatchItemWriter due to performance issue.

    public class MyItemWriter implements ItemWriter<List<MyDomainObject>> {

    @Override  
    public void write(List<? extends Lists<MyDomainObject>> items) {
    JpaItemWriter<MyDomainObject> writer = new JpaItemWriter<>();    
    for(List<MyDomainObject> o : items)
        {
          writer.write(o);
        }
      }
    }

Suggest a sample snippets which uses the JdbcBatchItemWriter to write the List of objects will helps. Tried using the ItemSqlParameterSourceProvider it did't help ending up in org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter exception


Solution

  • You example is not correct. You are creating a JpaItemWriter in the write method, so a new instance is created on each call to write. This is probably the cause of your performance issue.

    More importantly, lifecycle methods of the delegate writer (open/update/close) will not be honored (it is not the case for JpaItemWriter which does not implement ItemStream but this would be a problem if the delegate is an item stream). Your MyItemWriter implementation should be something like:

    public class MyItemWriter implements ItemWriter<List<MyDomainObject>> {
    
       private JpaItemWriter jpaItemWriter;
    
       public MyItemWriter(JpaItemWriter jpaItemWriter) {
          this. jpaItemWriter = jpaItemWriter;
       }
    
       @Override  
       public void write(List<? extends Lists<MyDomainObject>> items) {  
         for(List<MyDomainObject> o : items) {
           this. jpaItemWriter.write(o);
         }
       }
    }
    

    Now if you want to use the JdbcBatchItemWriter to write a list of lists, see Spring Batch - Using an ItemWriter with List of Lists.

    Edit: Added a sample code of how to set the delegate as requested in comments:

    @Bean
    public ListUnpackingItemWriter<T> itemWriter() {
        JdbcBatchItemWriter<T> jdbcBatchItemWriter = null; // configure your jdbcBatchItemWriter
        ListUnpackingItemWriter<T> listUnpackingItemWriter = new ListUnpackingItemWriter<>();
        listUnpackingItemWriter.setDelegate(jdbcBatchItemWriter);
        return listUnpackingItemWriter;
    }