首页 文章

Spring Batch CompositeItemWriter,在每个委托Writer的遍历结束时执行批处理以提高性能

提问于
浏览
0

在Spring批处理中,我的CompositeItemWriter使用多个ItemWriters将记录插入到多个表中,但是目前这些ItemWrite中的每一个都是批量插入的,如下所示

public class Item{
  public List<WarningObject> warnings
  public List<ErrorObject> errors
  public Long Id;
  public String data1;
  public String data2;
  public String data3;
  // getters and setters

}

我的作家配置

<bean id="compositeItemWriter" class="org.springframework.batch.item.support.CompositeItemWriter">
<property name="delegates">
<list>
    <ref bean="warningItemWriter"/>
    <ref bean="errorItemWriter"/>
    <ref bean="CustomJdbcItemWriter"/>
</list>
</property>
public class WarningItemWriter implements ItemWriter<Item>{

  @Autowire
   String sql;
  @AutoWire
   JdbcTemple jdbcTemplate;

  @Autowire
  ItemPreparedStatementSetter itemPreparedStatementSetter;

   @Override
   public void write(final List<? extends Item> items) throws Exception {
       for(Item item: items){

            jdbcTemplate.execute(sql,new PreparedStatementCallBack<int []>{
            @Override
                    public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                        for (WarningObject warning: item.getWarnings) {
                            itemPreparedStatementSetter.setValues(warning, ps);
                            ps.addBatch();
                        }
                        return ps.executeBatch();

             });
        }
   }

}

所以这很好用,但这并没有真正成为警告的批量插入

目前,它会批量插入我的一个项目的所有警告 . 但我理想的是希望在准备工作中添加每个项目的警告,并且一旦添加了所有项目的所有警告,我想调用 ps.executeBatch()

有人可以用这种方法帮助我吗?

1 回答

  • 0

    只需将外部循环移动到匿名类的内部:

    jdbcTemplate.execute(sql, new PreparedStatementCallBack<int []> {
        @Override
        public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (Item item: items) {
                for (WarningObject warning: item.getWarnings) {
                    itemPreparedStatementSetter.setValues(warning, ps);
                    ps.addBatch();
                 }
            }
            return ps.executeBatch();
        }
    });
    

相关问题