将通用的对 JDBC 进行操作的静态方法封装到 JdbcOperationSupport;使用 JdbcOperations 定义 SimpleJdbcTemplate 和 JdbcExecutor 的行为。

pull/1/head
ZhouXY108 2024-11-02 11:33:15 +08:00
parent 6b5bcf0b5c
commit 01fda84276
3 changed files with 1037 additions and 915 deletions

View File

@ -0,0 +1,471 @@
/*
* Copyright 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.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.Lists;
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
import xyz.zhouxy.plusone.commons.util.AssertTools;
import xyz.zhouxy.plusone.commons.util.OptionalTools;
/**
* JdbcOperationSupport
*
* <p>
* JDBC
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @since 1.0.0
*/
class JdbcOperationSupport {
// #region - query
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @param resultHandler {@link ResultSet}
*/
static <T> T query(Connection conn, String sql, Object[] params, ResultHandler<T> resultHandler)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertResultHandlerNotNull(resultHandler);
return queryInternal(conn, sql, params, resultHandler);
}
// #endregion
// #region - queryList
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @param rowMapper {@link ResultSet}
*/
static <T> List<T> queryList(Connection conn, String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertRowMapperNotNull(rowMapper);
return queryListInternal(conn, sql, params, rowMapper);
}
/**
* 使
*
* @param conn
* @param sql SQL
* @param params
* @param clazz
*/
static <T> List<T> queryList(Connection conn, String sql, Object[] params, Class<T> clazz)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertClazzNotNull(clazz);
return queryListInternal(conn, sql, params, (rs, rowNumber) -> rs.getObject(1, clazz));
}
// #endregion
// #region - queryFirst
/**
* {@link Optional}
*
* @param conn
* @param sql SQL
* @param params
* @param rowMapper {@link ResultSet}
*/
static <T> Optional<T> queryFirst(Connection conn, String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertRowMapperNotNull(rowMapper);
return queryFirstInternal(conn, sql, params, rowMapper);
}
/**
*
*
* @param <T>
* @param sql SQL
* @param params
* @param clazz
*/
static <T> Optional<T> queryFirst(Connection conn, String sql, Object[] params, Class<T> clazz)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertClazzNotNull(clazz);
return queryFirstInternal(conn, sql, params, (rs, rowNumber) -> rs.getObject(1, clazz));
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
*/
static Optional<String> queryFirstString(Connection conn, String sql, Object[] params)
throws SQLException {
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getString(1));
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
*/
static OptionalInt queryFirstInt(Connection conn, String sql, Object[] params)
throws SQLException {
Optional<Integer> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getInt(1));
return OptionalTools.toOptionalInt(result);
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
*/
static OptionalLong queryFirstLong(Connection conn, String sql, Object[] params)
throws SQLException {
Optional<Long> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getLong(1));
return OptionalTools.toOptionalLong(result);
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
*/
static OptionalDouble queryFirstDouble(Connection conn, String sql, Object[] params)
throws SQLException {
Optional<Double> result = queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getDouble(1));
return OptionalTools.toOptionalDouble(result);
}
/**
* {@link BigDecimal}
*
* @param conn
* @param sql SQL
* @param params
*/
static Optional<BigDecimal> queryFirstBigDecimal(Connection conn, String sql, Object[] params)
throws SQLException {
return queryFirst(conn, sql, params, (rs, rowNumber) -> rs.getBigDecimal(1));
}
// #endregion
// #region - update & batchUpdate
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @return
*/
static int update(Connection conn, String sql, Object[] params)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params);
return stmt.executeUpdate();
}
}
/**
* SQL keys
*
* @param conn
* @param sql SQL
* @param params
* @param rowMapper
*
* @return generated keys
* @throws SQLException SQL
*/
static <T> List<T> update(Connection conn, String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertRowMapperNotNull(rowMapper);
final List<T> result = new ArrayList<>();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
fillStatement(stmt, params);
stmt.executeUpdate();
try (ResultSet generatedKeys = stmt.getGeneratedKeys();) {
int rowNumber = 0;
while (generatedKeys.next()) {
T e = rowMapper.mapRow(generatedKeys, rowNumber++);
result.add(e);
}
}
return result;
}
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @param batchSize
*/
static List<int[]> batchUpdate(Connection conn, String sql, Collection<Object[]> params, int batchSize)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
if (params == null || params.isEmpty()) {
return Collections.emptyList();
}
int executeCount = params.size() / batchSize;
executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1);
List<int[]> result = Lists.newArrayListWithCapacity(executeCount);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int i = 0;
for (Object[] ps : params) {
i++;
fillStatement(stmt, ps);
stmt.addBatch();
if (i % batchSize == 0 || i >= params.size()) {
int[] n = stmt.executeBatch();
result.add(n);
stmt.clearBatch();
}
}
return result;
}
}
/**
* {@code exceptions}
*
* @param conn
* @param sql sql
* @param params
* @param batchSize
* @param exceptions
*/
static List<int[]> batchUpdateAndIgnoreException(Connection conn,
String sql, @Nullable Collection<Object[]> params, int batchSize,
List<Exception> exceptions)
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
AssertTools.checkArgument(CollectionTools.isNotEmpty(exceptions),
"The list used to store exceptions should be non-null and empty.");
if (params == null || params.isEmpty()) {
return Collections.emptyList();
}
int executeCount = params.size() / batchSize;
executeCount = (params.size() % batchSize == 0) ? executeCount : (executeCount + 1);
List<int[]> result = Lists.newArrayListWithCapacity(executeCount);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int i = 0;
for (Object[] ps : params) {
i++;
fillStatement(stmt, ps);
stmt.addBatch();
final int batchIndex = i % batchSize;
if (batchIndex == 0 || i >= params.size()) {
try {
int[] n = stmt.executeBatch();
result.add(n);
stmt.clearBatch();
}
catch (Exception e) {
int n = (i >= params.size() && batchIndex != 0) ? batchIndex : batchSize;
result.add(new int[n]);
stmt.clearBatch();
// 收集异常信息
exceptions.add(e);
}
}
}
return result;
}
}
// #endregion
// #region - internal
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @param resultHandler {@link ResultSet}
*/
private static <T> T queryInternal(@Nonnull Connection conn,
@Nonnull String sql,
@Nullable Object[] params,
@Nonnull ResultHandler<T> resultHandler)
throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params);
try (ResultSet rs = stmt.executeQuery()) {
return resultHandler.handle(rs);
}
}
}
/**
*
*
* @param conn
* @param sql SQL
* @param params
* @param rowMapper {@link ResultSet}
*/
private static <T> List<T> queryListInternal(@Nonnull Connection conn,
@Nonnull String sql,
@Nullable Object[] params,
@Nonnull RowMapper<T> rowMapper)
throws SQLException {
return queryInternal(conn, sql, params, rs -> {
List<T> result = new ArrayList<>();
int rowNumber = 0;
while (rs.next()) {
T e = rowMapper.mapRow(rs, rowNumber++);
result.add(e);
}
return result;
});
}
/**
* {@link Optional}
*
* @param conn
* @param sql SQL
* @param params
* @param rowMapper
*/
private static <T> Optional<T> queryFirstInternal(@Nonnull Connection conn,
@Nonnull String sql,
@Nullable Object[] params,
@Nonnull RowMapper<T> rowMapper)
throws SQLException {
return queryInternal(conn, sql, params, rs -> {
if (rs.next()) {
return Optional.ofNullable(rowMapper.mapRow(rs, 0));
}
return Optional.empty();
});
}
// #endregion
/**
*
*/
private static void fillStatement(@Nonnull PreparedStatement stmt, @Nullable Object[] params)
throws SQLException {
if (params != null && params.length > 0) {
Object param;
for (int i = 0; i < params.length; i++) {
param = params[i];
if (param instanceof java.sql.Date) {
stmt.setDate(i + 1, (java.sql.Date) param);
}
else if (param instanceof java.sql.Time) {
stmt.setTime(i + 1, (java.sql.Time) param);
}
else if (param instanceof java.sql.Timestamp) {
stmt.setTimestamp(i + 1, (java.sql.Timestamp) param);
}
else {
stmt.setObject(i + 1, param);
}
}
}
}
// #region - 参数校验
private static void assertConnectionNotNull(Connection conn) {
AssertTools.checkArgumentNotNull(conn, "The argument \"conn\" could not be null.");
}
private static void assertSqlNotNull(String sql) {
AssertTools.checkArgumentNotNull(sql, "The argument \"sql\" could not be null.");
}
private static void assertRowMapperNotNull(RowMapper<?> rowMapper) {
AssertTools.checkArgumentNotNull(rowMapper, "The argument \"rowMapper\" could not be null.");
}
private static void assertResultHandlerNotNull(ResultHandler<?> resultHandler) {
AssertTools.checkArgumentNotNull(resultHandler, "The argument \"resultHandler\" could not be null.");
}
private static void assertClazzNotNull(Class<?> clazz) {
AssertTools.checkArgumentNotNull(clazz, "The argument \"clazz\" could not be null.");
}
// #endregion
private JdbcOperationSupport() {
throw new IllegalStateException("Utility class");
}
}

View File

@ -0,0 +1,359 @@
package xyz.zhouxy.jdbc;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import javax.annotation.Nullable;
/**
* JdbcOperations
*
* <p>
* JdbcTemplate API
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @since 1.0.0
*/
interface JdbcOperations {
// #region - query
/**
*
*
* @param sql SQL
* @param params
* @param resultHandler {@link ResultSet}
*/
<T> T query(String sql, Object[] params, ResultHandler<T> resultHandler)
throws SQLException;
/**
*
*
* @param sql SQL
* @param resultHandler {@link ResultSet}
*/
<T> T query(String sql, ResultHandler<T> resultHandler)
throws SQLException;
// #endregion
// #region - queryList
/**
*
*
* @param sql SQL
* @param params
* @param rowMapper {@link ResultSet}
*/
<T> List<T> queryList(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException;
/**
* 使
*
* @param sql SQL
* @param params
* @param clazz
*/
<T> List<T> queryList(String sql, Object[] params, Class<T> clazz)
throws SQLException;
/**
* {@code Map<String, Object>}
*
* @param sql SQL
* @param params
*/
List<Map<String, Object>> queryList(String sql, Object[] params)
throws SQLException;
/**
* {@link DbRecord}
*
* @param sql SQL
* @param params
*/
List<DbRecord> queryRecordList(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @param rowMapper {@link ResultSet}
*/
<T> List<T> queryList(String sql, RowMapper<T> rowMapper)
throws SQLException;
/**
* 使
*
* @param sql SQL
* @param clazz
*/
<T> List<T> queryList(String sql, Class<T> clazz)
throws SQLException;
/**
* {@code Map<String, Object>}
*
* @param sql SQL
*/
List<Map<String, Object>> queryList(String sql)
throws SQLException;
/**
* {@link DbRecord}
*
* @param sql SQL
*/
List<DbRecord> queryRecordList(String sql)
throws SQLException;
// #endregion
// #region - queryFirst
/**
* {@link Optional}
*
* @param sql SQL
* @param params
* @param rowMapper {@link ResultSet}
*/
<T> Optional<T> queryFirst(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException;
/**
*
*
* @param <T>
* @param sql SQL
* @param params
* @param clazz
*/
<T> Optional<T> queryFirst(String sql, Object[] params, Class<T> clazz)
throws SQLException;
/**
* Map<String, Object>
*
* @param sql SQL
* @param params
*/
Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
throws SQLException;
/**
* DbRecord
*
* @param sql SQL
* @param params
*/
Optional<DbRecord> queryFirstRecord(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @param params
*/
Optional<String> queryFirstString(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @param params
*/
OptionalInt queryFirstInt(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @param params
*/
OptionalLong queryFirstLong(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @param params
*/
OptionalDouble queryFirstDouble(String sql, Object[] params)
throws SQLException;
/**
* {@link BigDecimal}
*
* @param sql SQL
* @param params
*/
Optional<BigDecimal> queryFirstBigDecimal(String sql, Object[] params)
throws SQLException;
/**
* {@link Optional}
*
* @param sql SQL
* @param rowMapper {@link ResultSet}
*/
<T> Optional<T> queryFirst(String sql, RowMapper<T> rowMapper)
throws SQLException;
/**
*
*
* @param <T>
* @param sql SQL
* @param clazz
*/
<T> Optional<T> queryFirst(String sql, Class<T> clazz)
throws SQLException;
/**
* Map<String, Object>
*
* @param sql SQL
*/
Optional<Map<String, Object>> queryFirst(String sql)
throws SQLException;
/**
* DbRecord
*
* @param sql SQL
*/
Optional<DbRecord> queryFirstRecord(String sql)
throws SQLException;
/**
*
*
* @param sql SQL
*/
Optional<String> queryFirstString(String sql)
throws SQLException;
/**
*
*
* @param sql SQL
*/
OptionalInt queryFirstInt(String sql)
throws SQLException;
/**
*
*
* @param sql SQL
*/
OptionalLong queryFirstLong(String sql)
throws SQLException;
/**
*
*
* @param sql SQL
*/
OptionalDouble queryFirstDouble(String sql)
throws SQLException;
/**
* {@link BigDecimal}
*
* @param sql SQL
*/
Optional<BigDecimal> queryFirstBigDecimal(String sql)
throws SQLException;
// #endregion
// #region - update & batchUpdate
/**
*
*
* @param sql SQL
* @param params
* @return
*/
int update(String sql, Object[] params)
throws SQLException;
/**
*
*
* @param sql SQL
* @return
*/
int update(String sql)
throws SQLException;
/**
* SQL keys
*
* @param sql SQL
* @param params
* @param rowMapper
*
* @return generated keys
* @throws SQLException SQL
*/
<T> List<T> update(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException;
/**
* SQL keys
*
* @param sql SQL
* @param rowMapper
*
* @return generated keys
* @throws SQLException SQL
*/
<T> List<T> update(String sql, RowMapper<T> rowMapper)
throws SQLException;
/**
*
*
* @param sql SQL
* @param params
* @param batchSize
*/
List<int[]> batchUpdate(String sql, @Nullable Collection<Object[]> params, int batchSize)
throws SQLException;
/**
* {@code exceptions}
*
* @param sql sql
* @param params
* @param batchSize
* @param exceptions
*/
List<int[]> batchUpdateAndIgnoreException(String sql, @Nullable Collection<Object[]> params,
int batchSize, List<Exception> exceptions)
throws SQLException;
// #endregion
}

File diff suppressed because it is too large Load Diff