Browse Source

Merge pull request #27154 from Li0n13

* pr/27154:
  Polish "Avoid calling executeBatch() with an empty batch"
  Avoid calling executeBatch() with an empty batch

Closes gh-27154
pull/31121/head
Stephane Nicoll 2 years ago
parent
commit
e18f1f5d9c
  1. 5
      spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
  2. 28
      spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java

5
spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java

@ -1036,10 +1036,13 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Executing SQL batch update [" + sql + "]"); logger.debug("Executing SQL batch update [" + sql + "]");
} }
int batchSize = pss.getBatchSize();
if (batchSize == 0) {
return new int[0];
}
int[] result = execute(sql, (PreparedStatementCallback<int[]>) ps -> { int[] result = execute(sql, (PreparedStatementCallback<int[]>) ps -> {
try { try {
int batchSize = pss.getBatchSize();
InterruptibleBatchPreparedStatementSetter ipss = InterruptibleBatchPreparedStatementSetter ipss =
(pss instanceof InterruptibleBatchPreparedStatementSetter ibpss ? ibpss : null); (pss instanceof InterruptibleBatchPreparedStatementSetter ibpss ? ibpss : null);
if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) { if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) {

28
spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java

@ -505,6 +505,34 @@ public class JdbcTemplateTests {
verify(this.connection, atLeastOnce()).close(); verify(this.connection, atLeastOnce()).close();
} }
@Test
public void testBatchUpdateWithPreparedStatementWithEmptyData() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {};
final int[] rowsAffected = new int[] {};
given(this.preparedStatement.executeBatch()).willReturn(rowsAffected);
mockDatabaseMetaData(true);
BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setInt(1, ids[i]);
}
@Override
public int getBatchSize() {
return ids.length;
}
};
JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
int[] actualRowsAffected = template.batchUpdate(sql, setter);
assertThat(actualRowsAffected.length == 0).as("executed 0 updates").isTrue();
verify(this.preparedStatement, never()).executeBatch();
}
@Test @Test
public void testInterruptibleBatchUpdate() throws Exception { public void testInterruptibleBatchUpdate() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";

Loading…
Cancel
Save