From 2d7bf83d8d262232c7af241d4761e24f72bbc637 Mon Sep 17 00:00:00 2001 From: Li0n13 Date: Sun, 11 Jul 2021 17:08:32 +0300 Subject: [PATCH] Avoid calling executeBatch() with an empty batch See gh-27154 --- .../jdbc/core/JdbcTemplate.java | 2 +- .../jdbc/core/JdbcTemplateTests.java | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java index 38c059330c..b07c70d218 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java @@ -1050,7 +1050,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { } ps.addBatch(); } - return ps.executeBatch(); + return batchSize > 0 ? ps.executeBatch() : new int[] {}; } else { List rowsAffected = new ArrayList<>(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java index 00eb07f0c3..d8a258eb5c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java @@ -505,6 +505,34 @@ public class JdbcTemplateTests { 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 public void testInterruptibleBatchUpdate() throws Exception { final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";