JdbcTemplate批处理更新出现问题



有一个简单的要求,我必须对更新查询的对象列表执行batchUpdate。

问题是,在运行代码后,在数据库表中,我只看到第一行得到了更新,其余的没有得到更新。下面是我为此使用的示例代码。

公共无效更新(列表列表({

String sql = "UPDATE table1 \rn"
+ "SET col1 = ?, col2 = ?, modified_on = UTC_TIMESTAMP() \rn"
+ "WHERE col3 = ? \rn"
+ "AND col4 = ? \rn"
+ "AND col5 = ? \rn"
+ "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中只有第一行被更新。我甚至试图改变列表中对象的顺序,结果仍然是一样的。然而,如果我在循环中为N大小的列表运行JdbcTemplate.update((方法N次,则会在DB中更新N条记录,但不会使用JdbcTemplate.batchUpdat((。我甚至尝试了NamedParameterJdbcTemplate的解决方案,但仍然存在相同的问题。此外,我在同一个DB中的其他表中执行batchUpdates的逻辑相同,并且此操作在同一代码流中进行编码。这样一切都很好。

关于为什么只更新第一条记录,有什么帮助吗?

每个记录都必须添加到最后一批中。您的代码中缺少。添加将解决问题的ps.addBatch()

String sql = "UPDATE table1 \rn"
+ "SET col1 = ?, col2 = ?, modified_on = UTC_TIMESTAMP() \rn"
+ "WHERE col3 = ? \rn"
+ "AND col4 = ? \rn"
+ "AND col5 = ? \rn"
+ "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());

ps.addBatch(); // Add this
}
});

最新更新