From 95f625d849d6869b82908637d21ace1b8929f9ee Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Sat, 27 May 2023 04:07:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=B1=BB=E5=90=8D=EF=BC=8C?= =?UTF-8?q?=E5=90=8C=E6=97=B6=E6=94=AF=E6=8C=81=E4=BA=8B=E5=8A=A1=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...{JdbcUtil.java => SimpleJdbcTemplate.java} | 64 ++++++--- .../plusone/commons/util/JdbcUtilTests.java | 61 --------- .../commons/util/SimpleJdbcTemplateTests.java | 123 ++++++++++++++++++ 3 files changed, 170 insertions(+), 78 deletions(-) rename src/main/java/xyz/zhouxy/plusone/commons/jdbc/{JdbcUtil.java => SimpleJdbcTemplate.java} (70%) delete mode 100644 src/test/java/xyz/zhouxy/plusone/commons/util/JdbcUtilTests.java create mode 100644 src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java diff --git a/src/main/java/xyz/zhouxy/plusone/commons/jdbc/JdbcUtil.java b/src/main/java/xyz/zhouxy/plusone/commons/jdbc/SimpleJdbcTemplate.java similarity index 70% rename from src/main/java/xyz/zhouxy/plusone/commons/jdbc/JdbcUtil.java rename to src/main/java/xyz/zhouxy/plusone/commons/jdbc/SimpleJdbcTemplate.java index e35f837..685ecdb 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/jdbc/JdbcUtil.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/jdbc/SimpleJdbcTemplate.java @@ -35,24 +35,25 @@ import org.apache.commons.lang3.ArrayUtils; import com.google.common.annotations.Beta; -import xyz.zhouxy.plusone.commons.util.MoreCollections; +import xyz.zhouxy.plusone.commons.util.Assert; +import xyz.zhouxy.plusone.commons.util.OptionalUtil; @Beta -public class JdbcUtil { +public class SimpleJdbcTemplate { - public static JdbcExecutor connect(Connection conn) { - return new JdbcExecutor(conn); + public static JdbcExecutorBak connect(final Connection conn) { + return new JdbcExecutorBak(conn); } - private JdbcUtil() { + private SimpleJdbcTemplate() { throw new IllegalStateException("Utility class"); } - public static class JdbcExecutor { + public static class JdbcExecutorBak { private final Connection conn; - public JdbcExecutor(Connection conn) { + public JdbcExecutorBak(Connection conn) { this.conn = conn; } @@ -74,6 +75,11 @@ public class JdbcUtil { } } + 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)); + } + public static final ResultMap> mapResultMap = rs -> { Map result = new HashMap<>(); ResultSetMetaData metaData = rs.getMetaData(); @@ -89,6 +95,10 @@ public class JdbcUtil { return query(sql, params, mapResultMap); } + public Optional> queryFirst(String sql, Object... params) throws SQLException { + return queryFirst(sql, params, mapResultMap); + } + public static final ResultMap recordResultMap = rs -> { DbRecord result = new DbRecord(); ResultSetMetaData metaData = rs.getMetaData(); @@ -104,26 +114,26 @@ public class JdbcUtil { return query(sql, params, recordResultMap); } + public Optional queryFirstRecord(String sql, Object... params) throws SQLException { + return queryFirst(sql, params, recordResultMap); + } + public Optional queryToString(String sql, Object... params) throws SQLException { - List result = query(sql, params, (ResultSet rs) -> rs.getString(1)); - return MoreCollections.isNotEmpty(result) ? Optional.ofNullable(result.get(0)) : Optional.empty(); + return queryFirst(sql, params, (ResultSet rs) -> rs.getString(1)); } public OptionalInt queryToInt(String sql, Object... params) throws SQLException { - List result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).intValue()); - Integer i = MoreCollections.isNotEmpty(result) ? result.get(0) : null; - return i != null ? OptionalInt.of(i) : OptionalInt.empty(); + Optional result = queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).intValue()); + return OptionalUtil.toOptionalInt(result); } public OptionalLong queryToLong(String sql, Object... params) throws SQLException { - List result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).longValue()); - Long i = MoreCollections.isNotEmpty(result) ? result.get(0) : null; - return i != null ? OptionalLong.of(i) : OptionalLong.empty(); + Optional result = queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).longValue()); + return OptionalUtil.toOptionalLong(result); } public Optional queryToBigDecimal(String sql, Object... params) throws SQLException { - List result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1)); - return MoreCollections.isNotEmpty(result) ? Optional.ofNullable(result.get(0)) : Optional.empty(); + return queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1)); } public int update(String sql, Object... params) throws SQLException { @@ -156,5 +166,25 @@ public class JdbcUtil { return result; } } + + public void tx(final Tx tx) throws Exception { + Assert.notNull(tx, "Tx can not be null."); + try { + this.conn.setAutoCommit(false); + tx.execute(); + conn.commit(); + conn.setAutoCommit(true); + } catch (Exception e) { + conn.rollback(); + conn.setAutoCommit(true); + throw e; + } + } + + @FunctionalInterface + public static interface Tx { + @SuppressWarnings("all") + void execute() throws Exception; + } } } diff --git a/src/test/java/xyz/zhouxy/plusone/commons/util/JdbcUtilTests.java b/src/test/java/xyz/zhouxy/plusone/commons/util/JdbcUtilTests.java deleted file mode 100644 index 0db69e0..0000000 --- a/src/test/java/xyz/zhouxy/plusone/commons/util/JdbcUtilTests.java +++ /dev/null @@ -1,61 +0,0 @@ -package xyz.zhouxy.plusone.commons.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import java.util.Optional; - -import javax.sql.DataSource; - -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; - -import xyz.zhouxy.plusone.commons.jdbc.DbRecord; -import xyz.zhouxy.plusone.commons.jdbc.JdbcUtil; - -class JdbcUtilTests { - - private static final Logger log = LoggerFactory.getLogger(JdbcUtilTests.class); - - static final String url = "jdbc:postgresql://localhost:5432/plusone"; - static final String username = "postgres"; - static final String password = "zhouxy108"; - - DataSource dataSource; - - String[] cStruct = { - "id", - "created_by", - "create_time", - "updated_by", - "update_time", - "status" - }; - - JdbcUtilTests() { - HikariConfig config = new HikariConfig(); - config.setJdbcUrl(url); - config.setUsername(username); - config.setPassword(password); - this.dataSource = new HikariDataSource(config); - } - - @Test - void testQuery() throws SQLException { - Connection conn = this.dataSource.getConnection(); - List rs = JdbcUtil.connect(conn).queryToRecordList( - "SELECT * FROM public.base_table WHERE id IN (?, ?, ?)", 501533, 501554, 544599); - assertTrue(3 > rs.size()); - for (DbRecord baseEntity : rs) { - log.info("id: {}", baseEntity.getValueAsLong("id")); - assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by")); - } - } -} diff --git a/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java b/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java new file mode 100644 index 0000000..ea24484 --- /dev/null +++ b/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java @@ -0,0 +1,123 @@ +package xyz.zhouxy.plusone.commons.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import javax.sql.DataSource; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.base.Splitter; +import com.google.common.io.Files; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import xyz.zhouxy.plusone.commons.jdbc.DbRecord; +import xyz.zhouxy.plusone.commons.jdbc.SimpleJdbcTemplate; + +class SimpleJdbcTemplateTests { + + private static final Logger log = LoggerFactory.getLogger(SimpleJdbcTemplateTests.class); + + DataSource dataSource; + + String[] cStruct = { + "id", + "created_by", + "create_time", + "updated_by", + "update_time", + "status" + }; + + SimpleJdbcTemplateTests() { + HikariConfig config = new HikariConfig(); + config.setJdbcUrl("jdbc:postgresql://localhost:5432/plusone"); + config.setUsername("postgres"); + config.setPassword("zhouxy108"); + this.dataSource = new HikariDataSource(config); + } + + @Test + void testQuery() throws SQLException { + try (Connection conn = this.dataSource.getConnection()) { + List rs = SimpleJdbcTemplate.connect(conn) + .queryToRecordList( + "SELECT * FROM public.base_table WHERE id IN (?, ?, ?)", + 501533, 501554, 544599); + assertTrue(3 > rs.size()); + for (DbRecord baseEntity : rs) { + log.info("id: {}", baseEntity.getValueAsLong("id")); + assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by")); + } + } + } + + @Test + void testSaveTxt() throws IOException, SQLException { + File file = new File("C:\\Users\\zhouxy\\Desktop", "Untitled-1.txt"); + assertTrue(file.exists()); + List recordStrList = Files.readLines(file, StandardCharsets.UTF_8); + if (MoreCollections.isEmpty(recordStrList)) { + log.info("file is empty."); + return; + } + + List recordList = new ArrayList<>(recordStrList.size()); + for (String rStr : recordStrList) { + List props = Splitter.on("|").splitToList(rStr) + .stream() + .map(s -> { + if (s == null) { + return null; + } + s = s.trim(); + return ("".equals(s) || "null".equals(s) || "NULL".equals(s)) ? null : s; + }) + .collect(Collectors.toList()); + DbRecord r = new DbRecord(); + for (int i = 0; i < cStruct.length; i++) { + r.put(cStruct[i], props.get(i)); + } + recordList.add(r); + } + + final String sql = "INSERT INTO test_table(id, created_by, create_time, updated_by, update_time, status) VALUES(?, ?, ?, ?, ?, ?)"; + final List params = recordList.stream() + .map(r -> new Object[] { + r.getValueAsString("id").orElse(null), + r.getValueAsString("created_by").orElse(null), + r.getValueAsString("create_time").orElse(null), + r.getValueAsString("updated_by").orElse(null), + r.getValueAsString("update_time").orElse(null), + r.getValueAsString("status").orElse(null) + }) + .collect(Collectors.toList()); + try (Connection conn = this.dataSource.getConnection()) { + SimpleJdbcTemplate.connect(conn).tx(() -> { + SimpleJdbcTemplate.connect(conn).batchUpdate(sql, params, 20); + + File targetFile = new File("C:\\Users\\zhouxy\\Desktop\\done", file.getName()); + boolean moveSucceeded = file.renameTo(targetFile); + if (!moveSucceeded) { + throw new IOException("文件移动失败:" + file.getName()); + } + }); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +}