JdbcTemplate batchUpdate的java问题
有一个简单的要求,我必须对更新查询的对象列表执行batchUpdate
问题是,在运行代码之后,在数据库表中,我只看到第一行得到更新,其余的并没有得到更新。下面是我为此使用的示例代码
公共作废更新(列表){
String sql = "UPDATE table1 \\\r\n"
+ "SET col1 = ?, col2 = ?, modified_on = UTC_TIMESTAMP() \\\r\n"
+ "WHERE col3 = ? \\\r\n"
+ "AND col4 = ? \\\r\n"
+ "AND col5 = ? \\\r\n"
+ "AND col6 = ?" // col5 will be different for different records.
int[] rowsArray = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public int getBatchSize() {
return list.size();
}
@Override
public void setValues(PreparedStatement ps, int index) throws SQLException {
SampleClass sampleClass = list.get(index);
ps.setString(1, sampleClass.getCol1());
ps.setString(2, sampleClass.getCol2());
ps.setString(3, sampleClass.getCol3());
ps.setString(4, sampleClass.getCol4());
ps.setString(5, sampleClass.getCol5());
ps.setString(6, sampleClass.getCol6());
}
});
}
如果我的列表大小为N,我甚至可以确认setValues()方法执行了N次。但仍然会执行batchUpdate,在DB中,只更新第一行。我甚至试图改变列表中对象的顺序,但结果仍然是一样的。但是,如果我运行JdbcTemplate。update()方法在循环中执行N次,对于N个大小的列表,N个记录在DB中更新,但不使用JdbcTemplate。BatchUpdate()。我甚至还尝试了NamedParameterJdbcTemplate的解决方案,但仍然存在相同的问题。另外,我在同一个DB中的其他表中执行batchUpdates的逻辑是相同的,并且此操作在相同的代码流中编码。这一切都很好
关于为什么只更新第一条记录有什么帮助吗
# 1 楼答案
每个记录都必须添加到最后一批中。你的代码里没有。添加
ps.addBatch()
可以解决你的问题