重构。Connection 不通过参数传进来,避免用户在传进 Connection 前做不可预料的操作。
parent
3ca9ad2be1
commit
fda69cea6b
2
pom.xml
2
pom.xml
|
@ -6,7 +6,7 @@
|
|||
|
||||
<groupId>xyz.zhouxy.jdbc</groupId>
|
||||
<artifactId>simple-jdbc</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<version>0.1.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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,110 +40,93 @@ 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 static String paramsToString(final Collection<Object[]> params) {
|
||||
if (params == null) {
|
||||
return "null";
|
||||
}
|
||||
if (params.isEmpty()) {
|
||||
return "[]";
|
||||
}
|
||||
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();
|
||||
}
|
||||
b.append(',');
|
||||
i++;
|
||||
}
|
||||
return b.append(']').toString();
|
||||
}
|
||||
|
||||
private SimpleJdbcTemplate() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static class JdbcExecutor {
|
||||
|
||||
private final Connection conn;
|
||||
|
||||
private JdbcExecutor(Connection conn) {
|
||||
this.conn = conn;
|
||||
}
|
||||
|
||||
public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException {
|
||||
try (PreparedStatement stmt = this.conn.prepareStatement(sql)) {
|
||||
fillStatement(stmt, params);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
List<T> result = new ArrayList<>();
|
||||
int rowNumber = 0;
|
||||
while (rs.next()) {
|
||||
T e = resultMap.map(rs, rowNumber++);
|
||||
result.add(e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap)
|
||||
throws SQLException {
|
||||
try (Connection conn = this.dataSource.getConnection()) {
|
||||
return JdbcExecutor.query(conn, sql, params, resultMap);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException {
|
||||
return query(sql, params, resultMap).stream().findFirst();
|
||||
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap)
|
||||
throws SQLException {
|
||||
try (Connection conn = this.dataSource.getConnection()) {
|
||||
return JdbcExecutor.queryFirst(conn, sql, params, resultMap);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> query(String sql, Object[] params) throws SQLException {
|
||||
return query(sql, params, ResultMap.mapResultMap);
|
||||
public List<Map<String, Object>> query(String sql, Object[] params)
|
||||
throws SQLException {
|
||||
try (Connection conn = this.dataSource.getConnection()) {
|
||||
return JdbcExecutor.query(conn, sql, params);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params) throws SQLException {
|
||||
return queryFirst(sql, params, ResultMap.mapResultMap);
|
||||
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
|
||||
throws SQLException {
|
||||
try (Connection conn = this.dataSource.getConnection()) {
|
||||
return JdbcExecutor.queryFirst(conn, sql, params);
|
||||
}
|
||||
}
|
||||
|
||||
public List<DbRecord> queryToRecordList(String sql, Object[] params) throws SQLException {
|
||||
return query(sql, params, ResultMap.recordResultMap);
|
||||
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 {
|
||||
return queryFirst(sql, params, ResultMap.recordResultMap);
|
||||
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 {
|
||||
return queryFirst(sql, params, (rs, rowNumber) -> rs.getString(1));
|
||||
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 {
|
||||
Optional<Integer> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getInt(1));
|
||||
return OptionalTools.toOptionalInt(result);
|
||||
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 {
|
||||
Optional<Long> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getLong(1));
|
||||
return OptionalTools.toOptionalLong(result);
|
||||
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 {
|
||||
Optional<Double> result = queryFirst(sql, params, (rs, rowNumber) -> rs.getDouble(1));
|
||||
return OptionalTools.toOptionalDouble(result);
|
||||
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 {
|
||||
return queryFirst(sql, params, (rs, rowNumber) -> rs.getBigDecimal(1));
|
||||
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 (PreparedStatement stmt = this.conn.prepareStatement(sql)) {
|
||||
fillStatement(stmt, params);
|
||||
return stmt.executeUpdate();
|
||||
public int update(String sql, Object[] params)
|
||||
throws SQLException {
|
||||
try (Connection conn = this.dataSource.getConnection()) {
|
||||
return JdbcExecutor.update(conn, sql, params);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -159,11 +142,254 @@ public class SimpleJdbcTemplate {
|
|||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public <E extends Exception> void commitIfTrue(@Nonnull final PredicateWithThrowable<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);
|
||||
if (operations.test(new JdbcExecutor(conn))) {
|
||||
conn.commit();
|
||||
}
|
||||
else {
|
||||
conn.rollback();
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
conn.rollback();
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
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;
|
||||
}
|
||||
|
||||
public static final class JdbcExecutor {
|
||||
|
||||
private final Connection conn;
|
||||
|
||||
private JdbcExecutor(Connection conn) {
|
||||
this.conn = conn;
|
||||
}
|
||||
|
||||
public <T> List<T> query(String sql, Object[] params, ResultMap<T> resultMap)
|
||||
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);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
List<T> result = new ArrayList<>();
|
||||
int rowNumber = 0;
|
||||
while (rs.next()) {
|
||||
T e = resultMap.map(rs, rowNumber++);
|
||||
result.add(e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Optional<T> queryFirst(Connection conn, String sql, Object[] params, ResultMap<T> resultMap)
|
||||
throws SQLException {
|
||||
return query(conn, sql, params, resultMap).stream().findFirst();
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> query(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return query(conn, sql, params, ResultMap.mapResultMap);
|
||||
}
|
||||
|
||||
private static Optional<Map<String, Object>> queryFirst(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return queryFirst(conn, sql, params, ResultMap.mapResultMap);
|
||||
}
|
||||
|
||||
private static List<DbRecord> queryToRecordList(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return query(conn, sql, params, ResultMap.recordResultMap);
|
||||
}
|
||||
|
||||
private static Optional<DbRecord> queryFirstRecord(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return queryFirst(conn, sql, params, ResultMap.recordResultMap);
|
||||
}
|
||||
|
||||
private static Optional<String> queryToString(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getString(1));
|
||||
}
|
||||
|
||||
private static OptionalInt queryToInt(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
Optional<Integer> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getInt(1));
|
||||
return OptionalTools.toOptionalInt(result);
|
||||
}
|
||||
|
||||
private static OptionalLong queryToLong(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
Optional<Long> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getLong(1));
|
||||
return OptionalTools.toOptionalLong(result);
|
||||
}
|
||||
|
||||
private static OptionalDouble queryToDouble(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
Optional<Double> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getDouble(1));
|
||||
return OptionalTools.toOptionalDouble(result);
|
||||
}
|
||||
|
||||
private static Optional<BigDecimal> queryToBigDecimal(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getBigDecimal(1));
|
||||
}
|
||||
|
||||
private static int update(Connection conn, String sql, Object[] params)
|
||||
throws SQLException {
|
||||
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
fillStatement(stmt, params);
|
||||
return stmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SQL 并更新后的数据
|
||||
*
|
||||
* @param sql 要执行的 SQL 语句
|
||||
* @param params 参数
|
||||
* @param resultMap 结果映射规则
|
||||
*
|
||||
* @return 更新的数据
|
||||
* @throws SQLException 执行 SQL 遇到异常情况将抛出
|
||||
*/
|
||||
private static <T> List<T> update(Connection conn, String sql, Object[] params, ResultMap<T> 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<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);
|
||||
stmt.executeUpdate();
|
||||
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;
|
||||
executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1);
|
||||
List<int[]> 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 <E extends Exception> void executeTransaction(@Nonnull final DbOperations<E> 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 <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 {
|
||||
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++) {
|
||||
|
|
|
@ -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,8 +60,7 @@ class SimpleJdbcTemplateTests {
|
|||
.WHERE(IN("id", ids))
|
||||
.toString();
|
||||
log.info(sql);
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
List<DbRecord> rs = SimpleJdbcTemplate.connect(conn)
|
||||
List<DbRecord> rs = jdbcTemplate
|
||||
.queryToRecordList(sql, ids);
|
||||
assertNotNull(rs);
|
||||
for (DbRecord baseEntity : rs) {
|
||||
|
@ -77,12 +69,10 @@ class SimpleJdbcTemplateTests {
|
|||
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInsert() throws SQLException {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
List<DbRecord> keys = SimpleJdbcTemplate.connect(conn).update(
|
||||
List<DbRecord> keys = jdbcTemplate.update(
|
||||
"INSERT INTO base_table(status, created_by) VALUES (?, ?)",
|
||||
buildParams(1, 886L),
|
||||
ResultMap.recordResultMap);
|
||||
|
@ -93,88 +83,97 @@ class SimpleJdbcTemplateTests {
|
|||
assertEquals(886L, result.getValueAsLong("created_by").getAsLong());
|
||||
assertTrue(result.get("id").isPresent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdate() throws SQLException {
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
List<DbRecord> keys = SimpleJdbcTemplate.connect(conn).update(
|
||||
List<DbRecord> keys = jdbcTemplate.update(
|
||||
"UPDATE base_table SET status = ?, version = version + 1, update_time = now(), updated_by = ? WHERE id = ? AND version = ?",
|
||||
buildParams(2, 886, 9, 0),
|
||||
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 -> {
|
||||
try {
|
||||
jdbcTemplate.executeTransaction((JdbcExecutor jdbc) -> {
|
||||
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();
|
||||
});
|
||||
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));
|
||||
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<Map<String, Object>> first = jdbcExecutor
|
||||
|
||||
Optional<Map<String, Object>> 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 -> {
|
||||
try {
|
||||
jdbcTemplate.commitIfTrue(jdbc -> {
|
||||
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();
|
||||
});
|
||||
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));
|
||||
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<Map<String, Object>> first = jdbcExecutor
|
||||
|
||||
Optional<Map<String, Object>> 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<Map<String, Object>> first = jdbcExecutor
|
||||
|
||||
Optional<Map<String, Object>> first = jdbcTemplate
|
||||
.queryFirst("SELECT * FROM base_table WHERE id = ?", buildParams(id));
|
||||
log.info("first: {}", first);
|
||||
assertTrue(first.isPresent());
|
||||
|
@ -202,9 +201,9 @@ class SimpleJdbcTemplateTests {
|
|||
|
||||
handleDate = handleDate.plusDays(1L);
|
||||
}
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
List<int[]> result = SimpleJdbcTemplate.connect(conn)
|
||||
.batchUpdate("insert into test_table (username, usage_date, usage_duration) values (?,?,?)",
|
||||
try {
|
||||
List<int[]> result = jdbcTemplate.batchUpdate(
|
||||
"insert into test_table (username, usage_date, usage_duration) values (?,?,?)",
|
||||
buildBatchParams(datas, item -> buildParams(
|
||||
item.getValueAsString("username"),
|
||||
item.getValueAsString("usage_date"),
|
||||
|
@ -213,7 +212,8 @@ class SimpleJdbcTemplateTests {
|
|||
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;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue