diff --git a/pom.xml b/pom.xml index 5ac365c..6cb554b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ xyz.zhouxy.jdbc simple-jdbc - 0.1.0-SNAPSHOT + 0.1.1-SNAPSHOT 8 diff --git a/src/main/java/xyz/zhouxy/jdbc/DbRecord.java b/src/main/java/xyz/zhouxy/jdbc/DbRecord.java index 7b1706a..e4ada93 100644 --- a/src/main/java/xyz/zhouxy/jdbc/DbRecord.java +++ b/src/main/java/xyz/zhouxy/jdbc/DbRecord.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 the original author or authors. + * Copyright 2022-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/xyz/zhouxy/jdbc/ParamBuilder.java b/src/main/java/xyz/zhouxy/jdbc/ParamBuilder.java index 90b3e51..3dccdce 100644 --- a/src/main/java/xyz/zhouxy/jdbc/ParamBuilder.java +++ b/src/main/java/xyz/zhouxy/jdbc/ParamBuilder.java @@ -1,3 +1,19 @@ +/* + * Copyright 2022-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package xyz.zhouxy.jdbc; import java.util.Arrays; diff --git a/src/main/java/xyz/zhouxy/jdbc/ResultMap.java b/src/main/java/xyz/zhouxy/jdbc/ResultMap.java index a009497..f7e6f7e 100644 --- a/src/main/java/xyz/zhouxy/jdbc/ResultMap.java +++ b/src/main/java/xyz/zhouxy/jdbc/ResultMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 the original author or authors. + * Copyright 2022-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java b/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java index aadf449..1f2d7f1 100644 --- a/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java +++ b/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2023 the original author or authors. + * Copyright 2022-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; @@ -32,6 +31,7 @@ import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import javax.annotation.Nonnull; +import javax.sql.DataSource; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; @@ -40,41 +40,175 @@ import xyz.zhouxy.plusone.commons.util.OptionalTools; public class SimpleJdbcTemplate { - public static JdbcExecutor connect(final Connection conn) { - return new JdbcExecutor(conn); + private final DataSource dataSource; + + public SimpleJdbcTemplate(DataSource dataSource) { + this.dataSource = dataSource; } - public static String paramsToString(Object[] params) { - return Arrays.toString(params); + public List query(String sql, Object[] params, ResultMap resultMap) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.query(conn, sql, params, resultMap); + } } - public static String paramsToString(final Collection params) { - if (params == null) { - return "null"; + public Optional queryFirst(String sql, Object[] params, ResultMap resultMap) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryFirst(conn, sql, params, resultMap); } - if (params.isEmpty()) { - return "[]"; + } + + public List> query(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.query(conn, sql, params); } - int iMax = params.size() - 1; - StringBuilder b = new StringBuilder(); - b.append('['); - int i = 0; - for (Object[] p : params) { - b.append(Arrays.toString(p)); - if (i == iMax) { - return b.append(']').toString(); + } + + public Optional> queryFirst(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryFirst(conn, sql, params); + } + } + + public List queryToRecordList(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToRecordList(conn, sql, params); + } + } + + public Optional queryFirstRecord(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryFirstRecord(conn, sql, params); + } + } + + public Optional queryToString(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToString(conn, sql, params); + } + } + + public OptionalInt queryToInt(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToInt(conn, sql, params); + } + } + + public OptionalLong queryToLong(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToLong(conn, sql, params); + } + } + + public OptionalDouble queryToDouble(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToDouble(conn, sql, params); + } + } + + public Optional queryToBigDecimal(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.queryToBigDecimal(conn, sql, params); + } + } + + public int update(String sql, Object[] params) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.update(conn, sql, params); + } + } + + /** + * 执行 SQL 并更新后的数据 + * + * @param sql 要执行的 SQL 语句 + * @param params 参数 + * @param resultMap 结果映射规则 + * + * @return 更新的数据 + * @throws SQLException 执行 SQL 遇到异常情况将抛出 + */ + public List update(@Nonnull String sql, @Nonnull Object[] params, ResultMap resultMap) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.update(conn, sql, params, resultMap); + } + } + + public List batchUpdate(String sql, Collection params, int batchSize) + throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + return JdbcExecutor.batchUpdate(conn, sql, params, batchSize); + } + } + + public void executeTransaction(@Nonnull final DbOperations operations) + throws SQLException, E { + Preconditions.checkNotNull(operations, "Operations can not be null."); + try (Connection conn = this.dataSource.getConnection()) { + final boolean autoCommit = conn.getAutoCommit(); + try { + conn.setAutoCommit(false); + operations.execute(new JdbcExecutor(conn)); + conn.commit(); + } + catch (Exception e) { + conn.rollback(); + throw e; + } + finally { + conn.setAutoCommit(autoCommit); } - b.append(','); - i++; } - return b.append(']').toString(); } - private SimpleJdbcTemplate() { - throw new IllegalStateException("Utility class"); + public void commitIfTrue(@Nonnull final PredicateWithThrowable operations) + throws SQLException, E { + Preconditions.checkNotNull(operations, "Operations can not be null."); + try (Connection conn = this.dataSource.getConnection()) { + final boolean autoCommit = conn.getAutoCommit(); + try { + conn.setAutoCommit(false); + if (operations.test(new JdbcExecutor(conn))) { + conn.commit(); + } + else { + conn.rollback(); + } + } + catch (Exception e) { + conn.rollback(); + throw e; + } + finally { + conn.setAutoCommit(autoCommit); + } + } } - public static class JdbcExecutor { + @FunctionalInterface + public interface DbOperations { + void execute(JdbcExecutor jdbcExecutor) throws E; + } + + @FunctionalInterface + public interface PredicateWithThrowable { + boolean test(JdbcExecutor jdbcExecutor) throws E; + } + + public static final class JdbcExecutor { private final Connection conn; @@ -82,8 +216,89 @@ public class SimpleJdbcTemplate { this.conn = conn; } - public List query(String sql, Object[] params, ResultMap resultMap) throws SQLException { - try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { + public List query(String sql, Object[] params, ResultMap resultMap) + throws SQLException { + return JdbcExecutor.query(this.conn, sql, params, resultMap); + } + + public Optional queryFirst(String sql, Object[] params, ResultMap resultMap) + throws SQLException { + return JdbcExecutor.queryFirst(this.conn, sql, params, resultMap); + } + + public List> query(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.query(this.conn, sql, params); + } + + public Optional> queryFirst(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryFirst(this.conn, sql, params); + } + + public List queryToRecordList(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToRecordList(this.conn, sql, params); + } + + public Optional queryFirstRecord(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryFirstRecord(this.conn, sql, params); + } + + public Optional queryToString(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToString(this.conn, sql, params); + } + + public OptionalInt queryToInt(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToInt(this.conn, sql, params); + } + + public OptionalLong queryToLong(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToLong(this.conn, sql, params); + } + + public OptionalDouble queryToDouble(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToDouble(this.conn, sql, params); + } + + public Optional queryToBigDecimal(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.queryToBigDecimal(this.conn, sql, params); + } + + public int update(String sql, Object[] params) + throws SQLException { + return JdbcExecutor.update(this.conn, sql, params); + } + + /** + * 执行 SQL 并更新后的数据 + * + * @param sql 要执行的 SQL 语句 + * @param params 参数 + * @param resultMap 结果映射规则 + * + * @return 更新的数据 + * @throws SQLException 执行 SQL 遇到异常情况将抛出 + */ + public List update(@Nonnull String sql, @Nonnull Object[] params, ResultMap resultMap) + throws SQLException { + return JdbcExecutor.update(this.conn, sql, params, resultMap); + } + + public List batchUpdate(String sql, Collection params, int batchSize) + throws SQLException { + return JdbcExecutor.batchUpdate(this.conn, sql, params, batchSize); + } + + private static List query(Connection conn, String sql, Object[] params, ResultMap resultMap) + throws SQLException { + try (PreparedStatement stmt = conn.prepareStatement(sql)) { fillStatement(stmt, params); try (ResultSet rs = stmt.executeQuery()) { List result = new ArrayList<>(); @@ -97,51 +312,62 @@ public class SimpleJdbcTemplate { } } - public Optional queryFirst(String sql, Object[] params, ResultMap resultMap) throws SQLException { - return query(sql, params, resultMap).stream().findFirst(); + private static Optional queryFirst(Connection conn, String sql, Object[] params, ResultMap resultMap) + throws SQLException { + return query(conn, sql, params, resultMap).stream().findFirst(); } - public List> query(String sql, Object[] params) throws SQLException { - return query(sql, params, ResultMap.mapResultMap); + private static List> query(Connection conn, String sql, Object[] params) + throws SQLException { + return query(conn, sql, params, ResultMap.mapResultMap); } - public Optional> queryFirst(String sql, Object[] params) throws SQLException { - return queryFirst(sql, params, ResultMap.mapResultMap); + private static Optional> queryFirst(Connection conn, String sql, Object[] params) + throws SQLException { + return queryFirst(conn, sql, params, ResultMap.mapResultMap); } - public List queryToRecordList(String sql, Object[] params) throws SQLException { - return query(sql, params, ResultMap.recordResultMap); + private static List queryToRecordList(Connection conn, String sql, Object[] params) + throws SQLException { + return query(conn, sql, params, ResultMap.recordResultMap); } - public Optional queryFirstRecord(String sql, Object[] params) throws SQLException { - return queryFirst(sql, params, ResultMap.recordResultMap); + private static Optional queryFirstRecord(Connection conn, String sql, Object[] params) + throws SQLException { + return queryFirst(conn, sql, params, ResultMap.recordResultMap); } - public Optional queryToString(String sql, Object[] params) throws SQLException { - return queryFirst(sql, params, (rs, rowNumber) -> rs.getString(1)); + private static Optional queryToString(Connection conn, String sql, Object[] params) + throws SQLException { + return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getString(1)); } - public OptionalInt queryToInt(String sql, Object[] params) throws SQLException { - Optional result = queryFirst(sql, params, (rs, rowNumber) -> rs.getInt(1)); + private static OptionalInt queryToInt(Connection conn, String sql, Object[] params) + throws SQLException { + Optional result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getInt(1)); return OptionalTools.toOptionalInt(result); } - public OptionalLong queryToLong(String sql, Object[] params) throws SQLException { - Optional result = queryFirst(sql, params, (rs, rowNumber) -> rs.getLong(1)); + private static OptionalLong queryToLong(Connection conn, String sql, Object[] params) + throws SQLException { + Optional result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getLong(1)); return OptionalTools.toOptionalLong(result); } - public OptionalDouble queryToDouble(String sql, Object[] params) throws SQLException { - Optional result = queryFirst(sql, params, (rs, rowNumber) -> rs.getDouble(1)); + private static OptionalDouble queryToDouble(Connection conn, String sql, Object[] params) + throws SQLException { + Optional result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getDouble(1)); return OptionalTools.toOptionalDouble(result); } - public Optional queryToBigDecimal(String sql, Object[] params) throws SQLException { - return queryFirst(sql, params, (rs, rowNumber) -> rs.getBigDecimal(1)); + private static Optional queryToBigDecimal(Connection conn, String sql, Object[] params) + throws SQLException { + return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getBigDecimal(1)); } - public int update(String sql, Object[] params) throws SQLException { - try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { + private static int update(Connection conn, String sql, Object[] params) + throws SQLException { + try (PreparedStatement stmt = conn.prepareStatement(sql)) { fillStatement(stmt, params); return stmt.executeUpdate(); } @@ -157,13 +383,13 @@ public class SimpleJdbcTemplate { * @return 更新的数据 * @throws SQLException 执行 SQL 遇到异常情况将抛出 */ - public List update(@Nonnull String sql, @Nonnull Object[] params, ResultMap resultMap) + private static List update(Connection conn, String sql, Object[] params, ResultMap resultMap) throws SQLException { Preconditions.checkNotNull(sql, "The sql could not be null."); Preconditions.checkNotNull(params, "The params could not be null."); Preconditions.checkNotNull(resultMap, "The resultMap could not be null."); final List result = new ArrayList<>(); - try (PreparedStatement stmt = this.conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { fillStatement(stmt, params); stmt.executeUpdate(); try (ResultSet generatedKeys = stmt.getGeneratedKeys();) { @@ -177,12 +403,13 @@ public class SimpleJdbcTemplate { } } - public List batchUpdate(String sql, Collection params, int batchSize) throws SQLException { + private static List batchUpdate(Connection conn, String sql, Collection params, int batchSize) + throws SQLException { int executeCount = params.size() / batchSize; executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1); List result = Lists.newArrayListWithCapacity(executeCount); - try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { + try (PreparedStatement stmt = conn.prepareStatement(sql)) { int i = 0; for (Object[] ps : params) { i++; @@ -198,57 +425,8 @@ public class SimpleJdbcTemplate { } } - public void executeTransaction(@Nonnull final DbOperations operations) - throws SQLException, E { - Preconditions.checkNotNull(operations, "Operations can not be null."); - final boolean autoCommit = this.conn.getAutoCommit(); - try { - this.conn.setAutoCommit(false); - operations.execute(this); - this.conn.commit(); - } - catch (Exception e) { - this.conn.rollback(); - throw e; - } - finally { - this.conn.setAutoCommit(autoCommit); - } - } - - public void commitIfTrue(@Nonnull final PredicateWithThrowable operations) - throws SQLException, E { - Preconditions.checkNotNull(operations, "Operations can not be null."); - final boolean autoCommit = this.conn.getAutoCommit(); - try { - this.conn.setAutoCommit(false); - if (operations.test(this)) { - this.conn.commit(); - } - else { - this.conn.rollback(); - } - } - catch (Exception e) { - this.conn.rollback(); - throw e; - } - finally { - this.conn.setAutoCommit(autoCommit); - } - } - - @FunctionalInterface - public interface DbOperations { - void execute(JdbcExecutor jdbcExecutor) throws E; - } - - @FunctionalInterface - public interface PredicateWithThrowable { - boolean test(JdbcExecutor jdbcExecutor) throws E; - } - - private static void fillStatement(PreparedStatement stmt, Object[] params) throws SQLException { + private static void fillStatement(PreparedStatement stmt, Object[] params) + throws SQLException { if (params != null && params.length > 0) { Object param; for (int i = 0; i < params.length; i++) { diff --git a/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java b/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java index b5a0654..73bc490 100644 --- a/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java +++ b/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static xyz.zhouxy.jdbc.ParamBuilder.*; import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN; -import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; @@ -39,14 +38,7 @@ class SimpleJdbcTemplateTests { private static final DataSource dataSource; - String[] cStruct = { - "id", - "created_by", - "create_time", - "updated_by", - "update_time", - "status" - }; + private static final SimpleJdbcTemplate jdbcTemplate; static { HikariConfig config = new HikariConfig(); @@ -56,6 +48,7 @@ class SimpleJdbcTemplateTests { config.setMaximumPoolSize(8); config.setConnectionTimeout(1000000); dataSource = new HikariDataSource(config); + jdbcTemplate = new SimpleJdbcTemplate(dataSource); } @Test @@ -67,114 +60,120 @@ class SimpleJdbcTemplateTests { .WHERE(IN("id", ids)) .toString(); log.info(sql); - try (Connection conn = dataSource.getConnection()) { - List rs = SimpleJdbcTemplate.connect(conn) - .queryToRecordList(sql, ids); - assertNotNull(rs); - for (DbRecord baseEntity : rs) { - // log.info("id: {}", baseEntity.getValueAsString("id")); // NOSONAR - log.info(baseEntity.toString()); - assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by")); - } + List rs = jdbcTemplate + .queryToRecordList(sql, ids); + assertNotNull(rs); + for (DbRecord baseEntity : rs) { + // log.info("id: {}", baseEntity.getValueAsString("id")); // NOSONAR + log.info(baseEntity.toString()); + assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by")); } } @Test void testInsert() throws SQLException { - try (Connection conn = dataSource.getConnection()) { - List keys = SimpleJdbcTemplate.connect(conn).update( - "INSERT INTO base_table(status, created_by) VALUES (?, ?)", - buildParams(1, 886L), - ResultMap.recordResultMap); - log.info("keys: {}", keys); - assertEquals(1, keys.size()); - DbRecord result = keys.get(0); - assertEquals(1, result.getValueAsInt("status").getAsInt()); - assertEquals(886L, result.getValueAsLong("created_by").getAsLong()); - assertTrue(result.get("id").isPresent()); - } + List keys = jdbcTemplate.update( + "INSERT INTO base_table(status, created_by) VALUES (?, ?)", + buildParams(1, 886L), + ResultMap.recordResultMap); + log.info("keys: {}", keys); + assertEquals(1, keys.size()); + DbRecord result = keys.get(0); + assertEquals(1, result.getValueAsInt("status").getAsInt()); + assertEquals(886L, result.getValueAsLong("created_by").getAsLong()); + assertTrue(result.get("id").isPresent()); } @Test void testUpdate() throws SQLException { - try (Connection conn = dataSource.getConnection()) { - List keys = SimpleJdbcTemplate.connect(conn).update( - "UPDATE base_table SET status = ?, version = version + 1, update_time = now(), updated_by = ? WHERE id = ? AND version = ?", - buildParams(2, 886, 9, 0), - ResultMap.recordResultMap); - log.info("keys: {}", keys); - } + List keys = jdbcTemplate.update( + "UPDATE base_table SET status = ?, version = version + 1, update_time = now(), updated_by = ? WHERE id = ? AND version = ?", + buildParams(2, 886, 571328822575109L, 0), + ResultMap.recordResultMap); + log.info("keys: {}", keys); } final IdWorker idGenerator = IdGenerator.getSnowflakeIdGenerator(0); @Test void testTransaction() throws SQLException { - try (Connection conn = dataSource.getConnection()) { + // 抛异常,回滚 + { long id = this.idGenerator.nextId(); - JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); - jdbcExecutor.executeTransaction(jdbc -> { - jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", - buildParams(id, 585757, LocalDateTime.now(), 0)); - throw new NullPointerException(); - }); - Optional> first = jdbcExecutor + try { + jdbcTemplate.executeTransaction((JdbcExecutor jdbc) -> { + jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", + buildParams(id, 100, LocalDateTime.now(), 0)); + throw new NullPointerException(); + }); + } + catch (NullPointerException e) { + // ignore + } + Optional> first = jdbcTemplate .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); log.info("first: {}", first); assertTrue(!first.isPresent()); } - try (Connection conn = dataSource.getConnection()) { + // 没有异常,提交事务 + { long id = this.idGenerator.nextId(); - JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); - jdbcExecutor.executeTransaction(jdbc -> { + jdbcTemplate.executeTransaction(jdbc -> { jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", - buildParams(id, 585757, LocalDateTime.now(), 0)); - // throw new NullPointerException(); // NOSONAR + buildParams(id, 101, LocalDateTime.now(), 0)); }); - Optional> first = jdbcExecutor + + Optional> first = jdbcTemplate .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); log.info("first: {}", first); assertTrue(first.isPresent()); } - try (Connection conn = dataSource.getConnection()) { + // 抛异常,回滚 + { long id = this.idGenerator.nextId(); - JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); - jdbcExecutor.commitIfTrue(jdbc -> { - jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", - buildParams(id, 585757, LocalDateTime.now(), 0)); - throw new NullPointerException(); - }); - Optional> first = jdbcExecutor + try { + jdbcTemplate.commitIfTrue(jdbc -> { + jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", + buildParams(id, 102, LocalDateTime.now(), 0)); + throw new NullPointerException(); + }); + } + catch (NullPointerException e) { + // ignore + } + Optional> first = jdbcTemplate .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); log.info("first: {}", first); assertTrue(!first.isPresent()); } - try (Connection conn = dataSource.getConnection()) { + // 返回 false,回滚 + { long id = this.idGenerator.nextId(); - JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); - jdbcExecutor.commitIfTrue(jdbc -> { + jdbcTemplate.commitIfTrue(jdbc -> { jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", - buildParams(id, 585757, LocalDateTime.now(), 0)); + buildParams(id, 103, LocalDateTime.now(), 0)); return false; }); - Optional> first = jdbcExecutor + + Optional> first = jdbcTemplate .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); log.info("first: {}", first); assertTrue(!first.isPresent()); } - try (Connection conn = dataSource.getConnection()) { + // 返回 true,提交事务 + { long id = this.idGenerator.nextId(); - JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); - jdbcExecutor.commitIfTrue(jdbc -> { + jdbcTemplate.commitIfTrue(jdbc -> { jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", - buildParams(id, 585757, LocalDateTime.now(), 0)); + buildParams(id, 104, LocalDateTime.now(), 0)); return true; }); - Optional> first = jdbcExecutor + + Optional> first = jdbcTemplate .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); log.info("first: {}", first); assertTrue(first.isPresent()); @@ -202,18 +201,19 @@ class SimpleJdbcTemplateTests { handleDate = handleDate.plusDays(1L); } - try (Connection conn = dataSource.getConnection()) { - List result = SimpleJdbcTemplate.connect(conn) - .batchUpdate("insert into test_table (username, usage_date, usage_duration) values (?,?,?)", - buildBatchParams(datas, item -> buildParams( - item.getValueAsString("username"), - item.getValueAsString("usage_date"), - item.getValueAsString("usage_duration"))), - 400); + try { + List result = jdbcTemplate.batchUpdate( + "insert into test_table (username, usage_date, usage_duration) values (?,?,?)", + buildBatchParams(datas, item -> buildParams( + item.getValueAsString("username"), + item.getValueAsString("usage_date"), + item.getValueAsString("usage_duration"))), + 400); long sum = Numbers.sum(ArrayTools.concatIntArray(result)); assertEquals(datas.size(), sum); log.info("sum: {}", sum); - } catch (Exception e) { + } + catch (Exception e) { e.printStackTrace(); throw e; }