在Spring batch中,我的CompositeItemWriter使用多个ItemWriters向多个表中插入记录,但目前这些ItemWriters中的每一个都是批量插入的,如下所示
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
}我的Writer配置
<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();
});
}
}
}因此,这可以很好地工作,但这并不是真正的批量插入警告
目前,它在批处理中插入我的一个项目的所有警告。但理想情况下,我希望将每一项的警告添加到preparedstatement中,一旦添加了所有项的所有警告,我希望调用ps.executeBatch()
有人能帮我解决这个问题吗?
发布于 2016-02-21 05:23:05
只需将外部循环移到匿名类的内部:
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();
}
});https://stackoverflow.com/questions/35528618
复制相似问题