From 19cf285d2b165c533f4e74b3c06b60c523e382be Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Mon, 18 Mar 2024 20:30:53 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E4=BB=A3=E7=A0=81=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xyz/zhouxy/jdbc/SimpleJdbcTemplate.java | 30 +++++----- .../zhouxy/jdbc/SimpleJdbcTemplateTests.java | 58 +++++++++++++++---- 2 files changed, 62 insertions(+), 26 deletions(-) diff --git a/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java b/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java index f237c1e..01eea2e 100644 --- a/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java +++ b/src/main/java/xyz/zhouxy/jdbc/SimpleJdbcTemplate.java @@ -42,8 +42,8 @@ import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; -import xyz.zhouxy.plusone.commons.util.MoreArrays; -import xyz.zhouxy.plusone.commons.util.MoreCollections; +import xyz.zhouxy.plusone.commons.collection.CollectionTools; +import xyz.zhouxy.plusone.commons.util.ArrayTools; import xyz.zhouxy.plusone.commons.util.OptionalUtil; @Beta @@ -107,8 +107,7 @@ public class SimpleJdbcTemplate { } public Optional queryFirst(String sql, Object[] params, ResultMap resultMap) throws SQLException { - List list = query(sql, params, resultMap); - return (list.isEmpty()) ? Optional.empty() : Optional.ofNullable(list.get(0)); + return query(sql, params, resultMap).stream().findFirst(); } public static final ResultMap> mapResultMap = (rs, rowNumber) -> { @@ -198,29 +197,30 @@ public class SimpleJdbcTemplate { stmt.clearBatch(); } } - return MoreArrays.concatIntArray(result); + return ArrayTools.concatIntArray(result); } } - public void tx(final IAtom atom) throws SQLException, T { + public void tx(final IAtom atom) throws SQLException, E { Preconditions.checkNotNull(atom, "Atom can not be null."); + final boolean autoCommit = this.conn.getAutoCommit(); try { this.conn.setAutoCommit(false); - atom.execute(); - conn.commit(); - conn.setAutoCommit(true); + atom.execute(this); + this.conn.commit(); } catch (Exception e) { - conn.rollback(); - conn.setAutoCommit(true); + this.conn.rollback(); throw e; } + finally { + this.conn.setAutoCommit(autoCommit); + } } @FunctionalInterface - public interface IAtom { - @SuppressWarnings("all") - void execute() throws SQLException, T; + public interface IAtom { + void execute(JdbcExecutor jdbcExecutor) throws SQLException, E; } private static void fillStatement(PreparedStatement stmt, Object[] params) throws SQLException { @@ -273,7 +273,7 @@ public class SimpleJdbcTemplate { public static List buildBatchParams(final Collection c, final Function func) { Preconditions.checkNotNull(c, "The collection can not be null."); Preconditions.checkNotNull(func, "The func can not be null."); - if (MoreCollections.isEmpty(c)) { + if (CollectionTools.isEmpty(c)) { return Collections.emptyList(); } return c.stream().map(func).collect(Collectors.toList()); diff --git a/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java b/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java index 5eaffb9..7b010e4 100644 --- a/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java +++ b/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java @@ -2,11 +2,13 @@ package xyz.zhouxy.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static xyz.zhouxy.jdbc.SimpleJdbcTemplate.ParamBuilder.*; import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN; import java.sql.Connection; import java.sql.SQLException; +import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; @@ -20,7 +22,10 @@ import org.slf4j.LoggerFactory; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; +import xyz.zhouxy.jdbc.SimpleJdbcTemplate.JdbcExecutor; import xyz.zhouxy.plusone.commons.sql.SQL; +import xyz.zhouxy.plusone.commons.util.IdGenerator; +import xyz.zhouxy.plusone.commons.util.IdWorker; class SimpleJdbcTemplateTests { @@ -39,7 +44,7 @@ class SimpleJdbcTemplateTests { static { HikariConfig config = new HikariConfig(); - config.setJdbcUrl("jdbc:postgresql://localhost:5432/jdbctest"); + config.setJdbcUrl("jdbc:postgresql://localhost:5432/plusone"); config.setUsername("postgres"); config.setPassword("zhouxy108"); config.setMaximumPoolSize(800); @@ -68,21 +73,52 @@ class SimpleJdbcTemplateTests { } } + final IdWorker idGenerator = IdGenerator.getSnowflakeIdGenerator(0); + @Test - void testTransaction() { + void testTransaction() throws SQLException { try (Connection conn = dataSource.getConnection()) { - SimpleJdbcTemplate.connect(conn) - .tx(() -> { - SimpleJdbcTemplate.connect(conn) - .update("INSERT INTO base_table (created_by, create_time, status) VALUES (?, now(), 0)", 585757); - Optional> first = SimpleJdbcTemplate.connect(conn) - .queryFirst("SELECT * FROM base_table WHERE created_by = ?", 585757); - log.info("first: {}", first); + long id = this.idGenerator.nextId(); + JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); + try { + jdbcExecutor.tx(jdbc -> { + jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", + buildParams(id, 585757, LocalDateTime.now(), 0)); throw new NullPointerException(); }); + } + catch (NullPointerException e) { + // ignore + } + catch (Exception e) { + e.printStackTrace(); + } + Optional> first = jdbcExecutor + .queryFirst("SELECT * FROM base_table WHERE id = ?", id); + log.info("first: {}", first); + assertTrue(!first.isPresent()); } - catch (Exception e) { - log.error(e.getMessage(), e); + + try (Connection conn = dataSource.getConnection()) { + long id = this.idGenerator.nextId(); + JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); + try { + jdbcExecutor.tx(jdbc -> { + jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", + buildParams(id, 585757, LocalDateTime.now(), 0)); + // throw new NullPointerException(); + }); + } + catch (NullPointerException e) { + // ignore + } + catch (Exception e) { + e.printStackTrace(); + } + Optional> first = jdbcExecutor + .queryFirst("SELECT * FROM base_table WHERE id = ?", id); + log.info("first: {}", first); + assertTrue(first.isPresent()); } } }