Writing List of Items using JdbcBatchItemWriter

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 09:40:36

问题


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


回答1:


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;
}


来源:https://stackoverflow.com/questions/52188198/writing-list-of-items-using-jdbcbatchitemwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!