重构。Connection 不通过参数传进来,避免用户在传进 Connection 前做不可预料的操作。

dev
ZhouXY108 2024-10-03 10:23:17 +08:00
parent 3ca9ad2be1
commit fda69cea6b
6 changed files with 379 additions and 185 deletions

View File

@ -6,7 +6,7 @@
<groupId>xyz.zhouxy.jdbc</groupId> <groupId>xyz.zhouxy.jdbc</groupId>
<artifactId>simple-jdbc</artifactId> <artifactId>simple-jdbc</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.1-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>8</maven.compiler.source>

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -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; package xyz.zhouxy.jdbc;
import java.util.Arrays; import java.util.Arrays;

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -32,6 +31,7 @@ import java.util.OptionalDouble;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.OptionalLong; import java.util.OptionalLong;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.sql.DataSource;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@ -40,41 +40,175 @@ import xyz.zhouxy.plusone.commons.util.OptionalTools;
public class SimpleJdbcTemplate { public class SimpleJdbcTemplate {
public static JdbcExecutor connect(final Connection conn) { private final DataSource dataSource;
return new JdbcExecutor(conn);
public SimpleJdbcTemplate(DataSource dataSource) {
this.dataSource = dataSource;
} }
public static String paramsToString(Object[] params) { public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap)
return Arrays.toString(params); throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.query(conn, sql, params, resultMap);
}
} }
public static String paramsToString(final Collection<Object[]> params) { public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap)
if (params == null) { throws SQLException {
return "null"; try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.queryFirst(conn, sql, params, resultMap);
} }
if (params.isEmpty()) { }
return "[]";
public List<Map<String, Object>> 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('['); public Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
int i = 0; throws SQLException {
for (Object[] p : params) { try (Connection conn = this.dataSource.getConnection()) {
b.append(Arrays.toString(p)); return JdbcExecutor.queryFirst(conn, sql, params);
if (i == iMax) { }
return b.append(']').toString(); }
public List<DbRecord> queryToRecordList(String sql, Object[] params)
throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.queryToRecordList(conn, sql, params);
}
}
public Optional<DbRecord> queryFirstRecord(String sql, Object[] params)
throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.queryFirstRecord(conn, sql, params);
}
}
public Optional<String> 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<BigDecimal> 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 <T> List<T> update(@Nonnull String sql, @Nonnull Object[] params, ResultMap<T> resultMap)
throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.update(conn, sql, params, resultMap);
}
}
public List<int[]> batchUpdate(String sql, Collection<Object[]> params, int batchSize)
throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
return JdbcExecutor.batchUpdate(conn, sql, params, batchSize);
}
}
public <E extends Exception> void executeTransaction(@Nonnull final DbOperations<E> 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() { public <E extends Exception> void commitIfTrue(@Nonnull final PredicateWithThrowable<E> operations)
throw new IllegalStateException("Utility class"); 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<E extends Exception> {
void execute(JdbcExecutor jdbcExecutor) throws E;
}
@FunctionalInterface
public interface PredicateWithThrowable<E extends Throwable> {
boolean test(JdbcExecutor jdbcExecutor) throws E;
}
public static final class JdbcExecutor {
private final Connection conn; private final Connection conn;
@ -82,8 +216,89 @@ public class SimpleJdbcTemplate {
this.conn = conn; this.conn = conn;
} }
public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException { public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap)
try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { throws SQLException {
return JdbcExecutor.query(this.conn, sql, params, resultMap);
}
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap)
throws SQLException {
return JdbcExecutor.queryFirst(this.conn, sql, params, resultMap);
}
public List<Map<String, Object>> query(String sql, Object[] params)
throws SQLException {
return JdbcExecutor.query(this.conn, sql, params);
}
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
throws SQLException {
return JdbcExecutor.queryFirst(this.conn, sql, params);
}
public List<DbRecord> queryToRecordList(String sql, Object[] params)
throws SQLException {
return JdbcExecutor.queryToRecordList(this.conn, sql, params);
}
public Optional<DbRecord> queryFirstRecord(String sql, Object[] params)
throws SQLException {
return JdbcExecutor.queryFirstRecord(this.conn, sql, params);
}
public Optional<String> 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<BigDecimal> 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 <T> List<T> update(@Nonnull String sql, @Nonnull Object[] params, ResultMap<T> resultMap)
throws SQLException {
return JdbcExecutor.update(this.conn, sql, params, resultMap);
}
public List<int[]> batchUpdate(String sql, Collection<Object[]> params, int batchSize)
throws SQLException {
return JdbcExecutor.batchUpdate(this.conn, sql, params, batchSize);
}
private static <T> List<T> query(Connection conn, String sql, Object[] params, ResultMap<T> resultMap)
throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params); fillStatement(stmt, params);
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
List<T> result = new ArrayList<>(); List<T> result = new ArrayList<>();
@ -97,51 +312,62 @@ public class SimpleJdbcTemplate {
} }
} }
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException { private static <T> Optional<T> queryFirst(Connection conn, String sql, Object[] params, ResultMap<T> resultMap)
return query(sql, params, resultMap).stream().findFirst(); throws SQLException {
return query(conn, sql, params, resultMap).stream().findFirst();
} }
public List<Map<String, Object>> query(String sql, Object[] params) throws SQLException { private static List<Map<String, Object>> query(Connection conn, String sql, Object[] params)
return query(sql, params, ResultMap.mapResultMap); throws SQLException {
return query(conn, sql, params, ResultMap.mapResultMap);
} }
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params) throws SQLException { private static Optional<Map<String, Object>> queryFirst(Connection conn, String sql, Object[] params)
return queryFirst(sql, params, ResultMap.mapResultMap); throws SQLException {
return queryFirst(conn, sql, params, ResultMap.mapResultMap);
} }
public List<DbRecord> queryToRecordList(String sql, Object[] params) throws SQLException { private static List<DbRecord> queryToRecordList(Connection conn, String sql, Object[] params)
return query(sql, params, ResultMap.recordResultMap); throws SQLException {
return query(conn, sql, params, ResultMap.recordResultMap);
} }
public Optional<DbRecord> queryFirstRecord(String sql, Object[] params) throws SQLException { private static Optional<DbRecord> queryFirstRecord(Connection conn, String sql, Object[] params)
return queryFirst(sql, params, ResultMap.recordResultMap); throws SQLException {
return queryFirst(conn, sql, params, ResultMap.recordResultMap);
} }
public Optional<String> queryToString(String sql, Object[] params) throws SQLException { private static Optional<String> queryToString(Connection conn, String sql, Object[] params)
return queryFirst(sql, params, (rs, rowNumber) -> rs.getString(1)); throws SQLException {
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getString(1));
} }
public OptionalInt queryToInt(String sql, Object[] params) throws SQLException { private static OptionalInt queryToInt(Connection conn, String sql, Object[] params)
Optional<Integer> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getInt(1)); throws SQLException {
Optional<Integer> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getInt(1));
return OptionalTools.toOptionalInt(result); return OptionalTools.toOptionalInt(result);
} }
public OptionalLong queryToLong(String sql, Object[] params) throws SQLException { private static OptionalLong queryToLong(Connection conn, String sql, Object[] params)
Optional<Long> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getLong(1)); throws SQLException {
Optional<Long> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getLong(1));
return OptionalTools.toOptionalLong(result); return OptionalTools.toOptionalLong(result);
} }
public OptionalDouble queryToDouble(String sql, Object[] params) throws SQLException { private static OptionalDouble queryToDouble(Connection conn, String sql, Object[] params)
Optional<Double> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getDouble(1)); throws SQLException {
Optional<Double> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getDouble(1));
return OptionalTools.toOptionalDouble(result); return OptionalTools.toOptionalDouble(result);
} }
public Optional<BigDecimal> queryToBigDecimal(String sql, Object[] params) throws SQLException { private static Optional<BigDecimal> queryToBigDecimal(Connection conn, String sql, Object[] params)
return queryFirst(sql, params, (rs, rowNumber) -> rs.getBigDecimal(1)); throws SQLException {
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getBigDecimal(1));
} }
public int update(String sql, Object[] params) throws SQLException { private static int update(Connection conn, String sql, Object[] params)
try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params); fillStatement(stmt, params);
return stmt.executeUpdate(); return stmt.executeUpdate();
} }
@ -157,13 +383,13 @@ public class SimpleJdbcTemplate {
* @return * @return
* @throws SQLException SQL * @throws SQLException SQL
*/ */
public <T> List<T> update(@Nonnull String sql, @Nonnull Object[] params, ResultMap<T> resultMap) private static <T> List<T> update(Connection conn, String sql, Object[] params, ResultMap<T> resultMap)
throws SQLException { throws SQLException {
Preconditions.checkNotNull(sql, "The sql could not be null."); Preconditions.checkNotNull(sql, "The sql could not be null.");
Preconditions.checkNotNull(params, "The params could not be null."); Preconditions.checkNotNull(params, "The params could not be null.");
Preconditions.checkNotNull(resultMap, "The resultMap could not be null."); Preconditions.checkNotNull(resultMap, "The resultMap could not be null.");
final List<T> result = new ArrayList<>(); final List<T> 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); fillStatement(stmt, params);
stmt.executeUpdate(); stmt.executeUpdate();
try (ResultSet generatedKeys = stmt.getGeneratedKeys();) { try (ResultSet generatedKeys = stmt.getGeneratedKeys();) {
@ -177,12 +403,13 @@ public class SimpleJdbcTemplate {
} }
} }
public List<int[]> batchUpdate(String sql, Collection<Object[]> params, int batchSize) throws SQLException { private static List<int[]> batchUpdate(Connection conn, String sql, Collection<Object[]> params, int batchSize)
throws SQLException {
int executeCount = params.size() / batchSize; int executeCount = params.size() / batchSize;
executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1); executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1);
List<int[]> result = Lists.newArrayListWithCapacity(executeCount); List<int[]> result = Lists.newArrayListWithCapacity(executeCount);
try (PreparedStatement stmt = this.conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int i = 0; int i = 0;
for (Object[] ps : params) { for (Object[] ps : params) {
i++; i++;
@ -198,57 +425,8 @@ public class SimpleJdbcTemplate {
} }
} }
public <E extends Exception> void executeTransaction(@Nonnull final DbOperations<E> operations) private static void fillStatement(PreparedStatement stmt, Object[] params)
throws SQLException, E { throws SQLException {
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 <E extends Exception> void commitIfTrue(@Nonnull final PredicateWithThrowable<E> 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<E extends Exception> {
void execute(JdbcExecutor jdbcExecutor) throws E;
}
@FunctionalInterface
public interface PredicateWithThrowable<E extends Throwable> {
boolean test(JdbcExecutor jdbcExecutor) throws E;
}
private static void fillStatement(PreparedStatement stmt, Object[] params) throws SQLException {
if (params != null && params.length > 0) { if (params != null && params.length > 0) {
Object param; Object param;
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {

View File

@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static xyz.zhouxy.jdbc.ParamBuilder.*; import static xyz.zhouxy.jdbc.ParamBuilder.*;
import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN; import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN;
import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -39,14 +38,7 @@ class SimpleJdbcTemplateTests {
private static final DataSource dataSource; private static final DataSource dataSource;
String[] cStruct = { private static final SimpleJdbcTemplate jdbcTemplate;
"id",
"created_by",
"create_time",
"updated_by",
"update_time",
"status"
};
static { static {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
@ -56,6 +48,7 @@ class SimpleJdbcTemplateTests {
config.setMaximumPoolSize(8); config.setMaximumPoolSize(8);
config.setConnectionTimeout(1000000); config.setConnectionTimeout(1000000);
dataSource = new HikariDataSource(config); dataSource = new HikariDataSource(config);
jdbcTemplate = new SimpleJdbcTemplate(dataSource);
} }
@Test @Test
@ -67,114 +60,120 @@ class SimpleJdbcTemplateTests {
.WHERE(IN("id", ids)) .WHERE(IN("id", ids))
.toString(); .toString();
log.info(sql); log.info(sql);
try (Connection conn = dataSource.getConnection()) { List<DbRecord> rs = jdbcTemplate
List<DbRecord> rs = SimpleJdbcTemplate.connect(conn) .queryToRecordList(sql, ids);
.queryToRecordList(sql, ids); assertNotNull(rs);
assertNotNull(rs); for (DbRecord baseEntity : rs) {
for (DbRecord baseEntity : rs) { // log.info("id: {}", baseEntity.getValueAsString("id")); // NOSONAR
// log.info("id: {}", baseEntity.getValueAsString("id")); // NOSONAR log.info(baseEntity.toString());
log.info(baseEntity.toString()); assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
}
} }
} }
@Test @Test
void testInsert() throws SQLException { void testInsert() throws SQLException {
try (Connection conn = dataSource.getConnection()) { List<DbRecord> keys = jdbcTemplate.update(
List<DbRecord> keys = SimpleJdbcTemplate.connect(conn).update( "INSERT INTO base_table(status, created_by) VALUES (?, ?)",
"INSERT INTO base_table(status, created_by) VALUES (?, ?)", buildParams(1, 886L),
buildParams(1, 886L), ResultMap.recordResultMap);
ResultMap.recordResultMap); log.info("keys: {}", keys);
log.info("keys: {}", keys); assertEquals(1, keys.size());
assertEquals(1, keys.size()); DbRecord result = keys.get(0);
DbRecord result = keys.get(0); assertEquals(1, result.getValueAsInt("status").getAsInt());
assertEquals(1, result.getValueAsInt("status").getAsInt()); assertEquals(886L, result.getValueAsLong("created_by").getAsLong());
assertEquals(886L, result.getValueAsLong("created_by").getAsLong()); assertTrue(result.get("id").isPresent());
assertTrue(result.get("id").isPresent());
}
} }
@Test @Test
void testUpdate() throws SQLException { void testUpdate() throws SQLException {
try (Connection conn = dataSource.getConnection()) { List<DbRecord> keys = jdbcTemplate.update(
List<DbRecord> keys = SimpleJdbcTemplate.connect(conn).update( "UPDATE base_table SET status = ?, version = version + 1, update_time = now(), updated_by = ? WHERE id = ? AND version = ?",
"UPDATE base_table SET status = ?, version = version + 1, update_time = now(), updated_by = ? WHERE id = ? AND version = ?", buildParams(2, 886, 571328822575109L, 0),
buildParams(2, 886, 9, 0), ResultMap.recordResultMap);
ResultMap.recordResultMap); log.info("keys: {}", keys);
log.info("keys: {}", keys);
}
} }
final IdWorker idGenerator = IdGenerator.getSnowflakeIdGenerator(0); final IdWorker idGenerator = IdGenerator.getSnowflakeIdGenerator(0);
@Test @Test
void testTransaction() throws SQLException { void testTransaction() throws SQLException {
try (Connection conn = dataSource.getConnection()) { // 抛异常,回滚
{
long id = this.idGenerator.nextId(); long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); try {
jdbcExecutor.executeTransaction(jdbc -> { jdbcTemplate.executeTransaction((JdbcExecutor jdbc) -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)",
buildParams(id, 585757, LocalDateTime.now(), 0)); buildParams(id, 100, LocalDateTime.now(), 0));
throw new NullPointerException(); throw new NullPointerException();
}); });
Optional<Map<String, Object>> first = jdbcExecutor }
catch (NullPointerException e) {
// ignore
}
Optional<Map<String, Object>> first = jdbcTemplate
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
log.info("first: {}", first); log.info("first: {}", first);
assertTrue(!first.isPresent()); assertTrue(!first.isPresent());
} }
try (Connection conn = dataSource.getConnection()) { // 没有异常,提交事务
{
long id = this.idGenerator.nextId(); long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); jdbcTemplate.executeTransaction(jdbc -> {
jdbcExecutor.executeTransaction(jdbc -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)",
buildParams(id, 585757, LocalDateTime.now(), 0)); buildParams(id, 101, LocalDateTime.now(), 0));
// throw new NullPointerException(); // NOSONAR
}); });
Optional<Map<String, Object>> first = jdbcExecutor
Optional<Map<String, Object>> first = jdbcTemplate
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
log.info("first: {}", first); log.info("first: {}", first);
assertTrue(first.isPresent()); assertTrue(first.isPresent());
} }
try (Connection conn = dataSource.getConnection()) { // 抛异常,回滚
{
long id = this.idGenerator.nextId(); long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); try {
jdbcExecutor.commitIfTrue(jdbc -> { jdbcTemplate.commitIfTrue(jdbc -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)",
buildParams(id, 585757, LocalDateTime.now(), 0)); buildParams(id, 102, LocalDateTime.now(), 0));
throw new NullPointerException(); throw new NullPointerException();
}); });
Optional<Map<String, Object>> first = jdbcExecutor }
catch (NullPointerException e) {
// ignore
}
Optional<Map<String, Object>> first = jdbcTemplate
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
log.info("first: {}", first); log.info("first: {}", first);
assertTrue(!first.isPresent()); assertTrue(!first.isPresent());
} }
try (Connection conn = dataSource.getConnection()) { // 返回 false回滚
{
long id = this.idGenerator.nextId(); long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); jdbcTemplate.commitIfTrue(jdbc -> {
jdbcExecutor.commitIfTrue(jdbc -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", 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; return false;
}); });
Optional<Map<String, Object>> first = jdbcExecutor
Optional<Map<String, Object>> first = jdbcTemplate
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
log.info("first: {}", first); log.info("first: {}", first);
assertTrue(!first.isPresent()); assertTrue(!first.isPresent());
} }
try (Connection conn = dataSource.getConnection()) { // 返回 true提交事务
{
long id = this.idGenerator.nextId(); long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn); jdbcTemplate.commitIfTrue(jdbc -> {
jdbcExecutor.commitIfTrue(jdbc -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)", 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; return true;
}); });
Optional<Map<String, Object>> first = jdbcExecutor
Optional<Map<String, Object>> first = jdbcTemplate
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id)); .queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
log.info("first: {}", first); log.info("first: {}", first);
assertTrue(first.isPresent()); assertTrue(first.isPresent());
@ -202,18 +201,19 @@ class SimpleJdbcTemplateTests {
handleDate = handleDate.plusDays(1L); handleDate = handleDate.plusDays(1L);
} }
try (Connection conn = dataSource.getConnection()) { try {
List<int[]> result = SimpleJdbcTemplate.connect(conn) List<int[]> result = jdbcTemplate.batchUpdate(
.batchUpdate("insert into test_table (username, usage_date, usage_duration) values (?,?,?)", "insert into test_table (username, usage_date, usage_duration) values (?,?,?)",
buildBatchParams(datas, item -> buildParams( buildBatchParams(datas, item -> buildParams(
item.getValueAsString("username"), item.getValueAsString("username"),
item.getValueAsString("usage_date"), item.getValueAsString("usage_date"),
item.getValueAsString("usage_duration"))), item.getValueAsString("usage_duration"))),
400); 400);
long sum = Numbers.sum(ArrayTools.concatIntArray(result)); long sum = Numbers.sum(ArrayTools.concatIntArray(result));
assertEquals(datas.size(), sum); assertEquals(datas.size(), sum);
log.info("sum: {}", sum); log.info("sum: {}", sum);
} catch (Exception e) { }
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw e; throw e;
} }