21 Commits

Author SHA1 Message Date
24ed544f97 build: 升级版本至 1.0.0-RC3 2026-06-05 21:30:21 +08:00
8b4f5bac65 test: 重构测试类 UpdateTest,补全 Statement 路径覆盖
- 按 update / updateAndReturnKeys 分组,内部再按 PreparedStatement
  (有参数)和 Statement(无参数)子路径组织,提升可维护性
- 重命名 3 个测试方法以消除歧义:
    testUpdateWithNullParams → testUpdateWithNullElement
    testUpdateWithParamsIsNull → testUpdateWithParamsNull
    testUpdateAndReturnKeysWithParamsIsNull → testUpdateAndReturnKeysWithParamsNull
- 新增 2 个测试用例补全 params=null 的 Statement 路径覆盖:
    testUpdateWithParamsNull
    testUpdateAndReturnKeysWithParamsNull
2026-06-05 21:17:12 +08:00
486d0c98c7 fix: 修复 updateAndReturnKeys 执行无参 SQL 无法获取生成的 key 的问题 2026-06-05 21:12:25 +08:00
f5909818c3 refactor: JdbcOperationSupport 中无参数 SQL 改用 Statement 执行
update、updateAndReturnKeys、queryInternal 三个方法根据是否有参数,分别走 PreparedStatement(有参数)或 Statement(无参数),避免无参数时不必要的预编译开销
2026-06-05 20:49:17 +08:00
3753aafd61 refactor: 提取 ResultHandler.mapToList 消除 ResultSet 遍历重复代码 2026-06-05 20:28:16 +08:00
f323d04d57 refactor: ParamBuilder#buildParams 中为常用数据类型添加短路处理
提取 buildParams 中的 lambda 为 handleItem 方法,并在 Optional 系列检测之前,为 null、CharSequence、Number、Boolean、Temporal 等高频类型增加提前返回逻辑,提升批量参数构建时的处理效率。

附带行为变化:CharSequence 实现类(如 StringBuilder/StringBuffer)现在会通过 toString() 转为 String 后再传递。
2026-06-05 20:08:08 +08:00
eabd5d7f77 docs: 更新项目简介 2026-06-02 23:31:24 +08:00
152094029e docs: 更新 DefaultBeanRowMapper 的描述以避免歧义 2026-06-02 23:21:26 +08:00
5b643291eb docs: 更新 README.md 2026-06-02 23:21:12 +08:00
492be49322 docs: 完善 SimpleJdbcTemplate 类文档注释 2026-05-31 05:56:32 +08:00
1a308ed30e refactor: 提取 TransactionTemplate,分离事务管理职责
将 executeTransaction / commitIfTrue 及 TransactionJdbcExecutor
从 SimpleJdbcTemplate 移至独立的 TransactionTemplate 类:

- 新增 TransactionTemplate,封装事务生命周期(开启/提交/回滚)
- SimpleJdbcTemplate 新增 transaction() 入口
- 更新 TransactionTest 适配新 API:template.transaction().execute()
- 更新 README.md 事务章节,说明 TransactionTemplate 使用方式
2026-05-31 05:48:51 +08:00
b639daca30 chore: 将版权年份从固定范围更新为包含当前时间的表述 2026-05-31 05:21:18 +08:00
20d10b84ee test: 添加Instant类型参数测试用例 2026-05-31 04:54:33 +08:00
8e543b40a6 test: 添加 ParamBuilder 参数构建工具类单元测试
- 验证 buildParams 方法对各种 Optional 类型的拆箱处理
- 测试普通参数、Optional<?>、OptionalInt、OptionalLong、OptionalDouble 的处理逻辑
- 验证 buildBatchParams 方法对集合的批量映射功能
- 测试空参数、边界情况和私有构造器的异常处理
2026-05-31 04:52:49 +08:00
3aff7509eb refactor: 简化 ParamBuilder 中的参数构建逻辑 2026-05-31 04:51:15 +08:00
3ad5718f8c feat: 优化为批量更新结果类的 toString 方法实现
- 为BatchUpdateErrorInfo类实现toString方法
- 重构BatchUpdateResult类的toString方法,调整字段顺序
2026-05-31 04:21:33 +08:00
8de546b7a6 docs: 更新批量更新相关类的JavaDoc文档
- 优化 BatchUpdateErrorInfo、BatchUpdateResult 类和成员的注释
- 为 BatchUpdateStatus 枚举添加详细的类注释和枚举值注释
2026-05-31 04:19:10 +08:00
9bf44c5494 refactor: 优化批量更新批次内索引计算逻辑
- 将 indexInBatch 改为 1-based 计算方式:批次触发条件改为 indexInBatch==batchSize,增强可读性
- 重命名 getUpdateCountsInternal 为 getUpdateCountsOnError,语义更清晰
- 精简方法参数,移除新方案下多余的入参 paramsSize/batchSize/itemIndex
- 补充关键变量注释
2026-05-31 03:21:12 +08:00
a51fcef845 docs: 更新文档完善使用说明和示例 2026-05-31 01:36:58 +08:00
cb9fd4ca75 build: 保持开发分支的版本后缀标识为 SNAPSHOT 2026-05-29 01:02:30 +08:00
ddddea0519 1.0.0-RC1 [plusone/simple-jdbc#9 (Gitea)] 2026-05-29 00:59:56 +08:00
14 changed files with 1047 additions and 374 deletions

258
README.md
View File

@@ -1,64 +1,54 @@
# SimpleJDBC
# Simple JDBC
对 JDBC 的简单封装
`Simple JDBC` 提供了一套轻量级的 JDBC 封装工具类,是作者在对传统遗留项目进行改造时设计。该项目未引入 ORM 框架,原本的数据库交互高度依赖原生 JDBC API导致存在大量冗余的样板代码Boilerplate Code。本项目通过抽象底层数据库操作简化了连接管理、SQL 执行与结果集处理流程,提升数据访问层的开发效率与代码可维护性
之前遇到的一个老项目,没有引入任何 ORM 框架,对数据库的操作几乎都在写原生 JDBC。故自己写了几个工具类对 JDBC 进行简单封装
> 注:本项目基于 [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) 开源协议发布
## 查询
---
### 查询方法
## ✨ 核心特性
- `query`**最基础的查询方法**。可使用 `ResultHandler` 将查询结果映射为 Java 对象
- `queryList`**查询列表**。可使用 `RowMapper` 将结果的每一行数据映射为 Java 对象,返回列表
- `queryFirst`**查询,并获取第一行数据**。一般可以结合 `LIMIT 1` 使用。可使用 `RowMapper` 将结果的第一行数据映射为 Java 对象,返回 `Optional`
- `queryBoolean`**获取第一行数据的第一个字段,并转换为布尔类型**。如果结果为空,则返回 `false`
- **轻量无依赖**:基于原生 JDBC 封装,无第三方重量级依赖
- **API 简洁**:提供丰富的快捷方法,大幅减少样板代码
- **灵活的映射**:支持自定义 `ResultHandler``RowMapper`,内置默认 Bean 映射策略
- **事务与批处理**:提供声明式的事务模板与完善的批量更新错误处理机制
- **线程安全**:核心模板类无状态设计,天然支持多线程环境。
### 结果映射
---
- `ResultHandler` 用于处理查询结果,自定义逻辑将完整的 `ResultSet` 映射为 Java 对象。 *结果可以是任意类型(包括集合)。*
- `RowMapper` 用于将 `ResultSet` 中的一行数据映射为 Java 对象。
- `RowMapper#HASH_MAP_MAPPER`:将 `ResultSet` 中的一行数据映射为 `HashMap`
- `RowMapper#beanRowMapper`:返回将 `ResultSet` 转换为 Java Bean 的默认实现。
## 📦 快速开始
## 更新
### 环境要求
- `int update`**执行 DML**,包括 `INSERT``UPDATE``DELETE` 等。返回受影响行数。
- `<T> List<T> update`**执行 DML**,自动生成的字段将使用 `rowMapper` 进行映射,并返回列表。
- `List<int[]> batchUpdate`**分批次执行 DML**,返回分批执行的结果。
- **JDK 8** 或更高版本
## 事务
### 添加 Maven 依赖
- `executeTransaction`**执行事务**。传入一个 `ThrowingConsumer` 函数,入参是一个 `JdbcOperations` 对象,在 `ThrowingConsumer` 内使用该入参执行 jdbc 操作。如果 `ThrowingConsumer` 内部有异常抛出,这些操作将被回滚。
将以下配置添加到您的 `pom.xml` 中:
- `commitIfTrue`**执行事务**。传入一个 `ThrowingPredicate` 函数,入参是一个 `JdbcOperations` 对象,在 `ThrowingPredicate` 内使用该入参执行 jdbc 操作。如果`ThrowingPredicate` 返回 `true`,则提交事务;如果返回 `false` 或有异常抛出,则回滚这些操作。
```xml
<dependency>
<groupId>xyz.zhouxy.jdbc</groupId>
<artifactId>simple-jdbc</artifactId>
<version>${simple-jdbc.version}</version>
</dependency>
```
## 参数构建
### 初始化
此项目中的所有查询和更新的方法,都**不使用可变长入参**,避免强行将 SQL 语句的参数列表放在最后,也避免和数组发生歧义。
### 构建参数列表
可使用 `ParamBuilder#buildParams` 构建 `Object[]` 数组作为 SQL 的参数列表。该方法会自动将 `Optional` 中的值“拆”出来。
### 批量构建参数列表
使用 `ParamBuilder#buildBatchParams`,将使用传入的函数,将集合中的每一个元素转为 `Object[]`,并返回一个 `List<Object[]>`
## 示例
创建 SimpleJdbcTemplate 对象
```java
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
```
查询
### 1. 查询操作
```java
// 查询(使用 ResultHandler 处理全部结果)
List<Account> list = jdbcTemplate.query(
// 1.1 基础查询(使用 ResultHandler 处理全部结果)
List<Account> accounts = jdbcTemplate.query(
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
buildParams("admin%", "0000"),
rs -> {
List<T> result = new ArrayList<>();
List<Account> result = new ArrayList<>();
while (rs.next()) {
result.add(new Account(
rs.getLong("id"),
@@ -73,20 +63,22 @@ List<Account> list = jdbcTemplate.query(
}
);
// 查询列表(单列)
// 1.2 查询列表(单列)
List<String> usernames = jdbcTemplate.queryList(
"SELECT username FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
buildParams("admin%", "0000"),
String.class
);
// 查询列表(使用 DefaultBeanRowMapper 进行映射)
List<Account> list = jdbcTemplate.queryList(
// 1.3 查询列表(使用内置 Bean 映射)
List<Account> mappedAccounts = jdbcTemplate.queryList(
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
buildParams("admin%", "0000"),
RowMapper.beanRowMapper(Account.class)
);
// 查询列表(使用自定义 RowMapper 进行映射)
List<Account> list = jdbcTemplate.queryList(
// 1.4 查询列表(使用自定义 RowMapper 映射)
List<Account> customMappedAccounts = jdbcTemplate.queryList(
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
buildParams("admin%", "0000"),
(rs, rowNum) -> new Account(
@@ -99,47 +91,55 @@ List<Account> list = jdbcTemplate.queryList(
)
);
// 查询行数据
// 1.5 查询行数据
Optional<Account> account = jdbcTemplate.queryFirst(
"SELECT * FROM account WHERE deleted = 0 AND id = ?",
buildParams(10000L),
(rs, rowNum) -> new Account(
rs.getLong("id"),
rs.getString("username"),
rs.getString("password"),
rs.getString("org_no"),
rs.getTimestamp("create_time"),
rs.getString("username")
// ... 省略其他字段
)
)
);
// 查询 boolean
// 1.6 查询 Boolean
boolean exists = jdbcTemplate.queryBoolean(
"SELECT EXISTS(SELECT 1 FROM account WHERE deleted = 0 AND id = ? LIMIT 1)",
"SELECT EXISTS(SELECT 1 FROM account WHERE deleted = 0 AND id = ?)",
buildParams(10000L)
);
// 1.7 无参数 SQL 可直接省略 params 参数
List<Account> allAccounts = jdbcTemplate.queryList(
"SELECT * FROM account WHERE deleted = 0",
RowMapper.beanRowMapper(Account.class)
);
```
更新
### 2. 更新操作
```java
// 执行 DML
// 2.1 执行常规 DML
int affectedRows = jdbcTemplate.update(
"UPDATE account SET deleted = 1 WHERE id = ?",
buildParams(10000L)
);
// 执行 DML并获取生成的主键
// 2.2 执行 DML 并获取生成的主键
// 注:按 JDBC 规范可获取自增 ID能否获取其他值取决于具体数据库及其 JDBC Driver 实现。
List<Pair<Long, LocalDateTime>> keys = jdbcTemplate.updateAndReturnKeys(
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
buildParams("admin", "123456", "0000"),
(rs, rowNum) -> Pair.of(
rs.getLong("id"),
rs.getObject("create_time", LocalDateTime.class)
rs.getLong("id"),
rs.getObject("create_time", LocalDateTime.class)
)
);
```
批量更新
### 3. 批量更新操作
```java
// 3.1 默认模式:遇错即中断
BatchUpdateResult result = jdbcTemplate.batchUpdate(
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
buildBatchParams(accountList, account -> buildParams(
@@ -147,21 +147,45 @@ BatchUpdateResult result = jdbcTemplate.batchUpdate(
account.getPassword(),
account.getOrgNo()
)),
100 // 每100条数据一个批次
100 // 每 100 条数据一个批次
);
// 3.2 静默模式:遇错不中断,全部执行完毕后统一检查
BatchUpdateResult quietResult = jdbcTemplate.batchUpdate(
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
buildBatchParams(accountList, account -> buildParams(
account.getUsername(),
account.getPassword(),
account.getOrgNo()
)),
100,
true // quietly = true遇错不中断
);
// 3.3 检查批量更新结果
if (quietResult.getStatus() == BatchUpdateStatus.COMPLETED_WITH_ERRORS) {
for (int idx : quietResult.getErrorBatchIndexes()) {
BatchUpdateErrorInfo err = quietResult.getBatchUpdateErrorInfo(idx);
System.err.println("批次 " + idx + " 失败: " + err.getCause().getMessage());
}
}
```
事务
### 4. 事务管理
```java
jdbcTemplate.executeTransaction(jdbc -> {
// 4.1 自动提交/回滚事务
jdbcTemplate.transaction().execute(jdbc -> {
...
jdbc.update(...);
...
jdbc.update(...);
...
// 内部无异常抛出则自动提交,抛出异常则自动回滚
});
jdbcTemplate.commitIfTrue(jdbc -> {
// 4.2 根据返回值控制事务
jdbcTemplate.transaction().commitIfTrue(jdbc -> {
...
jdbc.update(...);
...
@@ -182,4 +206,112 @@ jdbcTemplate.commitIfTrue(jdbc -> {
});
```
>**!!!本项目不比成熟的工具,如若使用请自行承担风险。建议仅作为 JDBC 的学习参考。**
---
## 🛠️ 参数构建
为避免与数组产生歧义并规范 API 设计,`JdbcOperations` 中的所有方法均不使用可变长参数Varargs而是统一使用 `Object[]` 作为参数传递。您可以使用内置的 `ParamBuilder` 快速构建参数。
### 1. 构建单条参数列表
使用 `ParamBuilder.buildParams(...)` 构建 `Object[]`。该方法会自动将 `Optional` 值进行拆箱处理。
```java
import static xyz.zhouxy.jdbc.ParamBuilder.buildParams;
buildParams("admin%", "0000"); // 返回 Object[]{"admin%", "0000"}
buildParams(Optional.of("hello")); // 返回 Object[]{"hello"}
buildParams(Optional.empty()); // 返回 Object[]{null}
```
### 2. 批量构建参数列表
使用 `ParamBuilder.buildBatchParams(collection, func)` 将集合中的每个元素转换为 `Object[]`,最终返回 `List<Object[]>`
```java
import static xyz.zhouxy.jdbc.ParamBuilder.buildBatchParams;
import static xyz.zhouxy.jdbc.ParamBuilder.buildParams;
List<Object[]> batchParams = buildBatchParams(accountList, account -> buildParams(
account.getUsername(),
account.getPassword(),
account.getOrgNo()
));
```
---
## 🔍 数据查询 (Query)
### 查询方法列表
| 方法签名 | 说明 |
| :--- | :--- |
| `query(sql, params, resultHandler)` | 最基础的查询,通过 `ResultHandler` 自定义完整的映射逻辑。 |
| `queryList(sql, params, rowMapper)` | 查询列表,通过 `RowMapper` 逐行映射。 |
| `queryList(sql, params, Class)` | 单列查询列表,每行提取第一列并转换为指定类型。 |
| `queryList(sql, params)` | 查询列表,每行自动转换为 `Map<String, Object>`。 |
| `queryFirst(sql, params, rowMapper)` | 查询第一行,通过 `RowMapper` 映射,返回 `Optional<T>`。 |
| `queryFirst(sql, params, Class)` | 查询第一行第一列,返回 `Optional<T>`。 |
| `queryFirst(sql, params)` | 查询第一行,返回 `Optional<Map<String, Object>>`。 |
| `queryBoolean(sql, params)` | 查询第一行第一列并转换为 `boolean`,若结果为空则返回 `false`。 |
*💡 提示:以上方法均有省略 `params` 的重载(如 `queryList(sql, rowMapper)`),适用于不含占位符的 SQL 语句。*
### 结果映射策略
- **`ResultHandler`**:处理完整的 `ResultSet`,允许自定义逻辑将结果集映射为任意类型(包括集合)。
- **`RowMapper`**:将 `ResultSet` 中的单行数据映射为 Java 对象。内置以下默认实现:
- `RowMapper.HASH_MAP_MAPPER`:将每行数据映射为 `HashMap<String, Object>`
- `DefaultBeanRowMapper`:将 `ResultSet` 中的一行数据映射为 Java Bean 的默认实现。使用反射获取类型信息、调用无参构造器和 `setter` 方法。**(注:实际生产中更建议针对目标类型自定义 `RowMapper` 以提升性能)**
- `RowMapper.beanRowMapper(Class)`:自动匹配 **属性名(小驼峰) ↔ 列名(小写蛇形)**
- `RowMapper.beanRowMapper(Class, Map<String, String>)`:通过 `Map` 自定义属性名与列名映射关系。
---
## ✏️ 数据更新 (Update)
所有更新方法同样提供了无参重载。
### 更新方法列表
| 方法签名 | 说明 |
| :--- | :--- |
| `update(sql, params)` | 执行 DMLINSERT / UPDATE / DELETE返回受影响的行数。 |
| `updateAndReturnKeys(sql, params, rowMapper)` | 执行 DML 并返回自动生成的键(如自增 ID通过 `RowMapper` 进行映射。 |
| `batchUpdate(sql, params, batchSize)` | 分批执行 DML遇到错误立即中断。 |
| `batchUpdate(sql, params, batchSize, quietly)` | 分批执行 DML`quietly=true`,则遇到错误不中断,直至全部执行完毕。 |
### 批量更新结果 (`BatchUpdateResult`)
`batchUpdate` 方法返回 `BatchUpdateResult` 对象,包含以下信息:
- `getStatus()`:批量更新的总状态(`SUCCESS` / `COMPLETED_WITH_ERRORS` / `INTERRUPTED`)。
- `getTotal()`:总数据量。
- `getBatchSize()`:批次大小
- `getBatchCount()`:总批次数。
- `getCompleteBatchCount()`:已完成的批次数。
- `getSuccessBatchCount()` / `getErrorBatchCount()`:成功 / 失败的批次数。
- `getRemainingBatchCount()`:(中断后)未执行的剩余批次数。
- `getUpdateCounts(batchIndex)`:获取指定批次更新结果。
- `getErrorBatchIndexes()`:获取所有出错的批次号.
- `getBatchUpdateErrorInfo(batchIndex)`:获取指定批次的详细错误信息。
- `getAllErrorsInfo()`:获取所有出错的批次的错误信息。
---
## 🔄 事务管理 (Transaction)
通过 `TransactionTemplate` 管理事务,可直接实例化或通过 `SimpleJdbcTemplate.transaction()` 获取。
- **`execute(consumer)`**:执行事务。传入 `ThrowingConsumer<JdbcOperations>`,若内部代码无异常抛出则自动提交,发生异常则回滚。
- **`commitIfTrue(predicate)`**:执行事务。传入 `ThrowingPredicate<JdbcOperations>`,根据返回值决定事务走向:返回 `true` 提交,返回 `false` 或抛出异常则回滚。
---
## ⚠️ 注意事项与适用场景
1. **风险提示**:本项目定位为轻量级工具,相较于成熟的 ORM 框架(如 MyBatis、Hibernate其功能覆盖面和生态相对有限。**在生产环境使用前,请务必进行充分的测试,使用风险自行承担。**
2. **线程安全**`SimpleJdbcTemplate` 本身无内部状态,是**线程安全**的。但请确保其底层依赖的 `DataSource`(如 HikariCP、Druid 等连接池)已正确配置并保证线程安全。
3. **连接管理**:每次数据库操作均会自动从 `DataSource` 获取连接,并在操作完成(或发生异常)后自动关闭,开发者无需手动管理连接的释放。
4. **适用场景**:中小型项目、内部工具、快速原型开发、未引入 ORM 框架的遗留系统改造、学习 JDBC 原理。

View File

@@ -5,7 +5,7 @@
<groupId>xyz.zhouxy.jdbc</groupId>
<artifactId>simple-jdbc</artifactId>
<version>1.0.0-RC1</version>
<version>1.0.0-RC3</version>
<name>Simple JDBC</name>
<description>对 JDBC 的简单封装。</description>

View File

@@ -16,31 +16,79 @@
package xyz.zhouxy.jdbc;
/**
* 批量更新错误信息
* 记录批量更新操作中某个批次的执行错误信息
*
* <p>当批量更新过程中某个批次执行失败时,该类用于封装出错批次的索引、
* 异常原因及其错误类型,便于调用方进行针对性的错误处理。
*
* @author ZhouXY
* @see BatchUpdateResult
*/
public class BatchUpdateErrorInfo {
/**
* 批次索引
*/
private final int batchIndex;
/**
* 错误原因
*/
private final Throwable cause;
/**
* 错误类型
*/
private final Class<? extends Throwable> errorType;
/**
* 构造一个批量更新错误信息实例。
*
* @param batchIndex 出错的批次索引
* @param cause 导致该批次执行失败的异常
*/
public BatchUpdateErrorInfo(int batchIndex, Throwable cause) {
this.batchIndex = batchIndex;
this.cause = cause;
this.errorType = cause.getClass();
}
/**
* 获取批次索引
*
* @return 批次索引
*/
public int getBatchIndex() {
return batchIndex;
}
/**
* 获取错误原因
*
* @return 错误原因
*/
public Throwable getCause() {
return cause;
}
/**
* 获取错误类型
*
* @return 错误类型
*/
public Class<? extends Throwable> getErrorType() {
return errorType;
}
/**
* 返回该错误信息的字符串表示,包含批次索引、错误类型和错误消息。
*
* @return 格式为 {@code "BatchUpdateErrorInfo{batchIndex=..., errorType=..., message=...}"} 的字符串
*/
@Override
public String toString() {
return "BatchUpdateErrorInfo{"
+ "batchIndex=" + batchIndex
+ ", errorType=" + errorType.getName()
+ ", message=" + cause.getMessage()
+ "}";
}
}

View File

@@ -22,20 +22,57 @@ import java.util.Map;
/**
* 批量更新结果
*
* <p>
* 封装 {@code batchUpdate} 操作的执行结果,包含:
* <ul>
* <li>整体执行状态 {@link BatchUpdateStatus}</li>
* <li>批次统计信息(总数据量、批次数、成功/失败/剩余批次数)</li>
* <li>各批次的更新结果及各错误批次的异常信息</li>
* </ul>
*
* @author ZhouXY
*
* @see BatchUpdateStatus
* @see BatchUpdateErrorInfo
* @see JdbcOperations#batchUpdate(String, java.util.Collection, int)
* @see JdbcOperations#batchUpdate(String, java.util.Collection, int, boolean)
*/
public class BatchUpdateResult {
/**
* 总数据量
*/
private final int total;
/**
* 批次数量
*/
private final int batchCount;
/**
* 批次大小
*/
private final int batchSize;
/**
* 本次分批更新的状态
*/
private BatchUpdateStatus status = BatchUpdateStatus.SUCCESS;
/**
* 所有批次的更新结果
*/
private Map<Integer, int[]> allUpdateCounts;
/**
* 所有出错的批次的错误信息
*/
private Map<Integer, BatchUpdateErrorInfo> allErrorsInfo;
/**
* 成功批次数量
*/
private int successBatchCount;
/**
* 完成批次数量
*/
private int completeBatchCount;
BatchUpdateResult(int total, int batchCount, int batchSize) {
@@ -76,7 +113,7 @@ public class BatchUpdateResult {
}
/**
* 获取批次更新结果
* 获取指定批次更新结果
*
* @param batchIndex 批次号
* @return 批次更新结果
@@ -87,7 +124,7 @@ public class BatchUpdateResult {
}
/**
* 获取错误批次号
* 获取所有出错的批次号
*
* @return 错误批次号
*/
@@ -96,7 +133,7 @@ public class BatchUpdateResult {
}
/**
* 获取错误批次信息
* 获取指定批次的错误信息
*
* @param batchIndex 批次号
* @return 批次错误信息
@@ -106,7 +143,7 @@ public class BatchUpdateResult {
}
/**
* 获取所有错误批次信息
* 获取所有出错的批次的错误信息
*
* @return 批次错误信息
*/
@@ -142,9 +179,9 @@ public class BatchUpdateResult {
}
/**
* 获取批更新状态
* 获取批更新状态
*
* @return 批更新状态
* @return 批更新状态
*/
public BatchUpdateStatus getStatus() {
return status;
@@ -180,19 +217,23 @@ public class BatchUpdateResult {
/**
* 获取剩余批次数量
*
* <p>
* 一般是中断后未执行的批次数量
*
* @return 剩余批次数量
*/
public int getRemainingBatchCount() {
return batchCount - successBatchCount - getErrorBatchCount();
}
/** {@inheritDoc} */
@Override
public String toString() {
return "BatchUpdateResult ["
+ "total=" + total
+ ", batchCount=" + batchCount
+ "status=" + status
+ ", total=" + total
+ ", batchSize=" + batchSize
+ ", status=" + status
+ ", batchCount=" + batchCount
+ ", completeBatchCount=" + completeBatchCount
+ ", successBatchCount=" + successBatchCount
+ ", errorBatchCount=" + getErrorBatchCount()

View File

@@ -20,7 +20,12 @@ import xyz.zhouxy.plusone.commons.base.IWithIntCode;
/**
* 批量更新状态
*
* <p>
* 用于表示批量更新操作的整体执行状态
*
* @author ZhouXY
* @see BatchUpdateResult
* @see BatchUpdateResult#getStatus()
*/
public enum BatchUpdateStatus implements IWithIntCode {
@@ -30,12 +35,20 @@ public enum BatchUpdateStatus implements IWithIntCode {
SUCCESS(0, "成功"),
/**
* 部分成功
* 执行完成,部分批次失败
*
* <p>
* 通常出现在 batchUpdate 的静默模式下:遇到执行失败的批次时不中断,继续执行后续批次,最终状态为此值。
*
* @see BatchUpdateResult#getErrorBatchIndexes()
*/
COMPLETED_WITH_ERRORS(-1, "部分成功"),
COMPLETED_WITH_ERRORS(-1, "执行完成,部分批次失败"),
/**
* 中断
*
* <p>
* 通常出现在 batchUpdate 的非静默模式下:遇到执行失败的批次时立即中断,不再执行后续批次。
*/
INTERRUPTED(-2, "中断"),
;
@@ -48,18 +61,26 @@ public enum BatchUpdateStatus implements IWithIntCode {
this.description = description;
}
/**
* {@inheritDoc}
*/
@Override
public int getCode() {
return code;
}
/**
* @return the description
* 获取状态的可读描述
*
* @return 描述信息
*/
public String getDescription() {
return description;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "BatchUpdateStatus ["

View File

@@ -42,7 +42,7 @@ import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
* DefaultBeanRowMapper
*
* <p>
* 默认实现的将 {@link ResultSet} 转换为 Java Bean 的 {@link RowMapper}。
* 将 {@link ResultSet} 转换为 Java Bean 的 {@link RowMapper} 的基础实现
* </p>
*
* <p>

View File

@@ -37,7 +37,7 @@ import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.Lists;
import xyz.zhouxy.plusone.commons.util.ArrayTools;
/**
* JdbcOperationSupport
@@ -162,9 +162,16 @@ class JdbcOperationSupport {
throws SQLException {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params);
return stmt.executeUpdate();
if (ArrayTools.isNotEmpty(params)) {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
fillStatement(stmt, params);
return stmt.executeUpdate();
}
}
else {
try (Statement stmt = conn.createStatement()) {
return stmt.executeUpdate(sql);
}
}
}
@@ -184,18 +191,24 @@ class JdbcOperationSupport {
assertConnectionNotNull(conn);
assertSqlNotNull(sql);
assertRowMapperNotNull(rowMapper);
final List<T> result = Lists.newArrayListWithCapacity(4);
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);
if (ArrayTools.isNotEmpty(params)) {
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
fillStatement(stmt, params);
stmt.executeUpdate();
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
final ResultHandler<List<T>> resultHandler = ResultHandler.mapToList(rowMapper);
return resultHandler.handle(generatedKeys);
}
}
}
else {
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
final ResultHandler<List<T>> resultHandler = ResultHandler.mapToList(rowMapper);
return resultHandler.handle(generatedKeys);
}
}
return result;
}
}
@@ -230,20 +243,26 @@ class JdbcOperationSupport {
final BatchUpdateResult result = new BatchUpdateResult(paramsSize, batchCount, batchSize);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// 表示第几条数据1, 2, 3, ..., paramsSize
int itemIndex = 0;
// 表示第几个批次0, 1, ..., batchCount-1
int batchIndex = 0;
for (Object[] ps : params) {
itemIndex++;
fillStatement(stmt, ps);
stmt.addBatch();
final int indexInBatch = itemIndex % batchSize;
if (indexInBatch == 0 || itemIndex >= paramsSize) {
// 表示当前数据在批次中的索引1, 2, 3, ..., batchSize-1, batchSize
final int indexInBatch = (itemIndex - 1) % batchSize + 1;
if (indexInBatch == batchSize || itemIndex == paramsSize) {
try {
int[] updateCounts = stmt.executeBatch();
result.recordSuccessBatch(batchIndex, updateCounts);
}
catch (Exception e) {
final int[] updateCounts = getUpdateCountsInternal(paramsSize, batchSize, itemIndex, indexInBatch, e);
final int[] updateCounts = getUpdateCountsOnError(indexInBatch, e);
result.recordErrorBatch(batchIndex, updateCounts, e);
if (!quietly) {
result.interrupt();
@@ -260,18 +279,13 @@ class JdbcOperationSupport {
}
}
private static int[] getUpdateCountsInternal(final int paramsSize,
final int batchSize,
final int itemIndex,
final int indexInBatch,
final Exception e) {
private static int[] getUpdateCountsOnError(final int indexInBatch, final Exception e) {
final int[] updateCounts;
if (e instanceof BatchUpdateException) {
updateCounts = ((BatchUpdateException) e).getUpdateCounts();
}
else {
int n = (itemIndex >= paramsSize && indexInBatch != 0) ? indexInBatch : batchSize;
updateCounts = new int[n];
updateCounts = new int[indexInBatch];
Arrays.fill(updateCounts, UNKNOWN_COUNT);
}
return updateCounts;
@@ -294,9 +308,17 @@ class JdbcOperationSupport {
@Nullable Object[] params,
@Nonnull ResultHandler<T> resultHandler)
throws SQLException {
try (PreparedStatement stmt = createPreparedStatementInternal(conn, sql, params);
ResultSet rs = stmt.executeQuery()) {
return resultHandler.handle(rs);
if (ArrayTools.isNotEmpty(params)) {
try (PreparedStatement stmt = createPreparedStatementInternal(conn, sql, params);
ResultSet rs = stmt.executeQuery()) {
return resultHandler.handle(rs);
}
}
else {
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
return resultHandler.handle(rs);
}
}
}
@@ -323,15 +345,7 @@ class JdbcOperationSupport {
@Nullable Object[] params,
@Nonnull RowMapper<T> rowMapper)
throws SQLException {
return queryInternal(conn, sql, params, rs -> {
List<T> result = Lists.newArrayList();
int rowNumber = 0;
while (rs.next()) {
T e = rowMapper.mapRow(rs, rowNumber++);
result.add(e);
}
return result;
});
return queryInternal(conn, sql, params, ResultHandler.mapToList(rowMapper));
}
/**

View File

@@ -17,6 +17,7 @@
package xyz.zhouxy.jdbc;
import java.sql.PreparedStatement;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -27,7 +28,6 @@ import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
import xyz.zhouxy.plusone.commons.util.ArrayTools;
@@ -51,27 +51,40 @@ public class ParamBuilder {
if (ArrayTools.isEmpty(params)) {
return EMPTY_OBJECT_ARRAY;
}
return buildParamsFromStream(Arrays.stream(params));
return Arrays.stream(params)
.map(ParamBuilder::handleItem)
.toArray();
}
private static Object[] buildParamsFromStream(Stream<?> stream) {
return stream
.map(param -> {
if (param instanceof Optional) {
return OptionalTools.orElseNull((Optional<?>) param);
}
if (param instanceof OptionalInt) {
return OptionalTools.toInteger((OptionalInt) param);
}
if (param instanceof OptionalLong) {
return OptionalTools.toLong((OptionalLong) param);
}
if (param instanceof OptionalDouble) {
return OptionalTools.toDouble((OptionalDouble) param);
}
return param;
})
.toArray();
private static Object handleItem(Object param) {
if (param == null) {
return null;
}
if (param instanceof CharSequence) {
return param.toString();
}
if (param instanceof Number) {
return param;
}
if (param instanceof Boolean) {
return param;
}
if (param instanceof Temporal) {
return param;
}
if (param instanceof Optional) {
return OptionalTools.orElseNull((Optional<?>) param);
}
if (param instanceof OptionalInt) {
return OptionalTools.toInteger((OptionalInt) param);
}
if (param instanceof OptionalLong) {
return OptionalTools.toLong((OptionalLong) param);
}
if (param instanceof OptionalDouble) {
return OptionalTools.toDouble((OptionalDouble) param);
}
return param;
}
public static <T> List<Object[]> buildBatchParams(final Collection<T> c, final Function<T, Object[]> func) {

View File

@@ -18,6 +18,8 @@ package xyz.zhouxy.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* ResultHandler
@@ -41,4 +43,26 @@ public interface ResultHandler<T> {
* @throws SQLException 数据库执行异常
*/
T handle(ResultSet resultSet) throws SQLException;
/**
* 创建一个返回 {@link List} 的 {@link ResultHandler},将 {@link ResultSet} 中的每一行
* 通过指定的 {@link RowMapper} 映射为对象,最终收集为一个 {@link List}。
*
* @param <T> 列表元素类型
* @param rowMapper 行映射器,用于将 {@link ResultSet} 的单行转换为对象
* @return 返回 {@code List<T>} 的 {@code ResultHandler}
* @since 1.0.0
* @see RowMapper
*/
static <T> ResultHandler<List<T>> mapToList(RowMapper<T> rowMapper) {
return resultSet -> {
List<T> result = new ArrayList<>();
int rowNumber = 0;
while (resultSet.next()) {
T e = rowMapper.mapRow(resultSet, rowNumber++);
result.add(e);
}
return result;
};
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2022-2026 ZhouXY
* Copyright 2022-present ZhouXY
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,28 +26,43 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import xyz.zhouxy.plusone.commons.function.ThrowingConsumer;
import xyz.zhouxy.plusone.commons.function.ThrowingPredicate;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* SimpleJdbcTemplate
* JDBC 操作的模板类,对原生 JDBC 进行轻量封装,提供查询、更新、批量操作等便捷方法。
*
* <p>
* 对 JDBC 的简单封装,方便数据库操作,支持事务,支持批量操作,支持自定义结果集映射
* </p>
* 主要能力:
* <ul>
* <li>查询:支持 {@link ResultHandler} 自定义结果处理、{@link RowMapper} 行映射等多种方式</li>
* <li>更新:执行 INSERT / UPDATE / DELETE支持返回自增主键</li>
* <li>批量操作:通过 {@link #batchUpdate} 分批执行 DML支持静默模式遇错继续
* 非静默模式(遇错即中断)</li>
* <li>事务:通过 {@link #transaction()} 获取 {@link TransactionTemplate} 执行</li>
* </ul>
*
* <p>
* 线程安全:本类无内部可变状态,线程安全。所依赖的 {@link DataSource}
* 需自行保证线程安全。
*
* @author ZhouXY
* @since 1.0.0
* @see JdbcOperations
* @see TransactionTemplate
* @see ParamBuilder
*/
public class SimpleJdbcTemplate implements JdbcOperations {
@Nonnull
private final DataSource dataSource;
@Nonnull
private final TransactionTemplate transactionTemplate;
public SimpleJdbcTemplate(@Nonnull DataSource dataSource) {
AssertTools.checkNotNull(dataSource);
this.dataSource = dataSource;
this.transactionTemplate = new TransactionTemplate(dataSource);
}
// #region - query
@@ -184,203 +199,10 @@ public class SimpleJdbcTemplate implements JdbcOperations {
// #region - transaction
/**
* 执行事务。如果未发生异常,则提交事务;当有异常发生时,回滚事务
*
* <p>
* operations 中使用 JdbcExecutor 实参进行 JDBC 操作,这些操作在一个连接中
* </p>
*
* @param <E> 异常类型
* @param operations 事务操作
* @throws SQLException SQL 异常
* @throws TransactionException 事务异常。事务中的异常会包装在该异常中。
*/
public <E extends Exception> void executeTransaction(
@Nonnull final ThrowingConsumer<JdbcOperations, E> operations)
throws TransactionException, SQLException {
AssertTools.checkNotNull(operations, "Operations can not be null.");
try (Connection conn = this.dataSource.getConnection()) {
final boolean autoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(false);
operations.accept(new TransactionJdbcExecutor(conn));
conn.commit();
}
catch (Exception e) {
try {
conn.rollback();
}
catch (SQLException ex) {
e.addSuppressed(ex);
}
throw new TransactionException(e);
}
finally {
conn.setAutoCommit(autoCommit);
}
}
}
/**
* 执行事务。
* 如果 {@code operations} 返回 {@code true},则提交事务;
* 如果抛出异常,或返回 {@code false},则回滚事务
*
* @param <E> 事务中的异常
* @param operations 事务操作
* @throws SQLException 数据库异常
* @throws TransactionException 事务异常。事务中的异常会包装在该异常中。
*/
public <E extends Exception> void commitIfTrue(
@Nonnull final ThrowingPredicate<JdbcOperations, E> operations)
throws SQLException, TransactionException {
AssertTools.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 TransactionJdbcExecutor(conn))) {
conn.commit();
}
else {
conn.rollback();
}
}
catch (Exception e) {
try {
conn.rollback();
}
catch (SQLException ex) {
e.addSuppressed(ex);
}
throw new TransactionException(e);
}
finally {
conn.setAutoCommit(autoCommit);
}
}
public TransactionTemplate transaction() {
return this.transactionTemplate;
}
// #endregion
private static final class TransactionJdbcExecutor implements JdbcOperations {
private final Connection conn;
private TransactionJdbcExecutor(Connection conn) {
this.conn = conn;
}
// #region - query
/** {@inheritDoc} */
@Override
public <T> T query(String sql, Object[] params, ResultHandler<T> resultHandler)
throws SQLException {
return JdbcOperationSupport.query(this.conn, sql, params, resultHandler);
}
// #endregion
// #region - queryList
/** {@inheritDoc} */
@Override
public <T> List<T> queryList(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, rowMapper);
}
/** {@inheritDoc} */
@Override
public <T> List<T> queryList(String sql, Object[] params, Class<T> clazz)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, clazz);
}
/** {@inheritDoc} */
@Override
public List<Map<String, Object>> queryList(String sql, Object[] params)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, RowMapper.HASH_MAP_MAPPER);
}
// #endregion
// #region - queryFirst
/** {@inheritDoc} */
@Override
public <T> Optional<T> queryFirst(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
final T result = JdbcOperationSupport.queryFirst(this.conn, sql, params, rowMapper);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public <T> Optional<T> queryFirst(String sql, Object[] params, Class<T> clazz)
throws SQLException {
final T result = JdbcOperationSupport.queryFirst(this.conn, sql, params, clazz);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
throws SQLException {
final Map<String, Object> result = JdbcOperationSupport
.queryFirst(this.conn, sql, params, RowMapper.HASH_MAP_MAPPER);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public boolean queryBoolean(String sql, Object[] params)
throws SQLException {
final Boolean result = JdbcOperationSupport
.queryFirst(this.conn, sql, params, Boolean.class);
return Boolean.TRUE.equals(result);
}
// #endregion
// #region - update & batchUpdate
/** {@inheritDoc} */
@Override
public int update(String sql, Object[] params)
throws SQLException {
return JdbcOperationSupport.update(this.conn, sql, params);
}
/** {@inheritDoc} */
@Override
public <T> List<T> updateAndReturnKeys(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
return JdbcOperationSupport.updateAndReturnKeys(this.conn, sql, params, rowMapper);
}
/** {@inheritDoc} */
@Override
public BatchUpdateResult batchUpdate(String sql, @Nullable Collection<Object[]> params, int batchSize)
throws SQLException {
return JdbcOperationSupport.batchUpdate(this.conn, sql, params, batchSize, false);
}
/** {@inheritDoc} */
@Override
public BatchUpdateResult batchUpdate(String sql,
@Nullable Collection<Object[]> params,
int batchSize,
boolean quietly) throws SQLException {
return JdbcOperationSupport
.batchUpdate(this.conn, sql, params, batchSize, quietly);
}
// #endregion
}
}

View File

@@ -0,0 +1,271 @@
/*
* Copyright 2026-present ZhouXY
*
* 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.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import xyz.zhouxy.plusone.commons.function.ThrowingConsumer;
import xyz.zhouxy.plusone.commons.function.ThrowingPredicate;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* 事务模板,提供事务执行能力。
*
* <p>
* 负责管理事务的生命周期:开启、提交、回滚、恢复自动提交。
* 事务内的 JDBC 操作通过 {@link JdbcOperations} 接口进行,
* 所有操作共享同一个数据库连接。
* </p>
*
* <p>使用示例:</p>
* <pre>{@code
* TransactionTemplate tx = new TransactionTemplate(dataSource);
*
* // 消费者模式:无异常自动提交
* tx.execute(ops -> {
* ops.update("INSERT INTO ...", buildParams(...));
* ops.update("UPDATE ...", buildParams(...));
* });
*
* // 谓词模式:返回 true 提交false 回滚
* tx.commitIfTrue(ops -> {
* ops.update("UPDATE ...", buildParams(...));
* return ops.queryBoolean("SELECT ...", buildParams(...));
* });
* }</pre>
*
* @author ZhouXY
* @since 1.1.0
*/
public class TransactionTemplate {
@Nonnull
private final DataSource dataSource;
public TransactionTemplate(@Nonnull DataSource dataSource) {
AssertTools.checkNotNull(dataSource);
this.dataSource = dataSource;
}
/**
* 执行事务。如果未发生异常,则提交事务;当有异常发生时,回滚事务
*
* <p>
* operations 中使用 JdbcExecutor 实参进行 JDBC 操作,这些操作在一个连接中
* </p>
*
* @param <E> 异常类型
* @param operations 事务操作
* @throws SQLException SQL 异常
* @throws TransactionException 事务异常。事务中的异常会包装在该异常中。
*/
public <E extends Exception> void execute(
@Nonnull final ThrowingConsumer<JdbcOperations, E> operations)
throws TransactionException, SQLException {
AssertTools.checkNotNull(operations, "Operations can not be null.");
try (Connection conn = this.dataSource.getConnection()) {
final boolean autoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(false);
operations.accept(new TransactionJdbcExecutor(conn));
conn.commit();
}
catch (Exception e) {
rollbackSilently(conn, e);
throw new TransactionException(e);
}
finally {
conn.setAutoCommit(autoCommit);
}
}
}
/**
* 执行事务。
* 如果 {@code operations} 返回 {@code true},则提交事务;
* 如果抛出异常,或返回 {@code false},则回滚事务
*
* @param <E> 事务中的异常
* @param operations 事务操作
* @throws SQLException 数据库异常
* @throws TransactionException 事务异常。事务中的异常会包装在该异常中。
*/
public <E extends Exception> void commitIfTrue(
@Nonnull final ThrowingPredicate<JdbcOperations, E> operations)
throws SQLException, TransactionException {
AssertTools.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 TransactionJdbcExecutor(conn))) {
conn.commit();
}
else {
conn.rollback();
}
}
catch (Exception e) {
rollbackSilently(conn, e);
throw new TransactionException(e);
}
finally {
conn.setAutoCommit(autoCommit);
}
}
}
private void rollbackSilently(Connection conn, Exception e) {
try {
conn.rollback();
}
catch (SQLException ex) {
e.addSuppressed(ex);
}
}
// #region - TransactionJdbcExecutor
private static final class TransactionJdbcExecutor implements JdbcOperations {
private final Connection conn;
private TransactionJdbcExecutor(Connection conn) {
this.conn = conn;
}
// #region - query
/** {@inheritDoc} */
@Override
public <T> T query(String sql, Object[] params, ResultHandler<T> resultHandler)
throws SQLException {
return JdbcOperationSupport.query(this.conn, sql, params, resultHandler);
}
// #endregion
// #region - queryList
/** {@inheritDoc} */
@Override
public <T> List<T> queryList(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, rowMapper);
}
/** {@inheritDoc} */
@Override
public <T> List<T> queryList(String sql, Object[] params, Class<T> clazz)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, clazz);
}
/** {@inheritDoc} */
@Override
public List<Map<String, Object>> queryList(String sql, Object[] params)
throws SQLException {
return JdbcOperationSupport.queryList(this.conn, sql, params, RowMapper.HASH_MAP_MAPPER);
}
// #endregion
// #region - queryFirst
/** {@inheritDoc} */
@Override
public <T> Optional<T> queryFirst(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
final T result = JdbcOperationSupport.queryFirst(this.conn, sql, params, rowMapper);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public <T> Optional<T> queryFirst(String sql, Object[] params, Class<T> clazz)
throws SQLException {
final T result = JdbcOperationSupport.queryFirst(this.conn, sql, params, clazz);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public Optional<Map<String, Object>> queryFirst(String sql, Object[] params)
throws SQLException {
final Map<String, Object> result = JdbcOperationSupport
.queryFirst(this.conn, sql, params, RowMapper.HASH_MAP_MAPPER);
return Optional.ofNullable(result);
}
/** {@inheritDoc} */
@Override
public boolean queryBoolean(String sql, Object[] params)
throws SQLException {
final Boolean result = JdbcOperationSupport
.queryFirst(this.conn, sql, params, Boolean.class);
return Boolean.TRUE.equals(result);
}
// #endregion
// #region - update & batchUpdate
/** {@inheritDoc} */
@Override
public int update(String sql, Object[] params)
throws SQLException {
return JdbcOperationSupport.update(this.conn, sql, params);
}
/** {@inheritDoc} */
@Override
public <T> List<T> updateAndReturnKeys(String sql, Object[] params, RowMapper<T> rowMapper)
throws SQLException {
return JdbcOperationSupport.updateAndReturnKeys(this.conn, sql, params, rowMapper);
}
/** {@inheritDoc} */
@Override
public BatchUpdateResult batchUpdate(String sql, @Nullable Collection<Object[]> params, int batchSize)
throws SQLException {
return JdbcOperationSupport.batchUpdate(this.conn, sql, params, batchSize, false);
}
/** {@inheritDoc} */
@Override
public BatchUpdateResult batchUpdate(String sql,
@Nullable Collection<Object[]> params,
int batchSize,
boolean quietly) throws SQLException {
return JdbcOperationSupport
.batchUpdate(this.conn, sql, params, batchSize, quietly);
}
// #endregion
}
// #endregion
}

View File

@@ -0,0 +1,227 @@
package xyz.zhouxy.jdbc.test;
import static org.junit.jupiter.api.Assertions.*;
import static xyz.zhouxy.jdbc.ParamBuilder.*;
import java.util.Arrays;
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 java.util.function.Function;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.jdbc.ParamBuilder;
/**
* ParamBuilder 单元测试。
*
* <p>验证 {@code buildParams} 对各种 Optional 类型的拆箱处理,
* 以及 {@code buildBatchParams} 对集合的批量映射逻辑。</p>
*
* @see xyz.zhouxy.jdbc.ParamBuilder
*/
@DisplayName("ParamBuilder 参数构建测试")
class ParamBuilderTest {
// ====================================================================
// #region - buildParams空参数
// --------------------------------------------------------------------
@Test
@DisplayName("buildParams无参 / null / 空数组均返回 EMPTY_OBJECT_ARRAY")
void testBuildParamsEmpty() {
assertSame(EMPTY_OBJECT_ARRAY, buildParams());
assertSame(EMPTY_OBJECT_ARRAY, buildParams((Object[]) null));
assertSame(EMPTY_OBJECT_ARRAY, buildParams(new Object[0]));
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - buildParams普通参数
// --------------------------------------------------------------------
@Test
@DisplayName("buildParams普通参数原样返回null 元素保留README 示例)")
void testBuildParamsPlain() {
Object[] result = buildParams("admin%", "0000", null, 100, 200L, 3.14, true);
assertEquals(7, result.length);
assertEquals("admin%", result[0]);
assertEquals("0000", result[1]);
assertNull(result[2]);
assertEquals(100, result[3]);
assertEquals(200L, result[4]);
assertEquals(3.14, result[5]);
assertEquals(true, result[6]);
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - buildParamsOptional<?>
// --------------------------------------------------------------------
@Test
@DisplayName("buildParamsOptional.of 拆箱为值Optional.empty 拆箱为 nullREADME 示例)")
void testBuildParamsOptional() {
// README: Optional.of("hello") → "hello", Optional.empty() → null
Object[] result = buildParams(Optional.of("hello"), Optional.empty(), Optional.of(42));
assertEquals(3, result.length);
assertEquals("hello", result[0]);
assertNull(result[1]);
assertEquals(42, result[2]);
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - buildParamsOptionalInt / OptionalLong / OptionalDouble
// --------------------------------------------------------------------
@Test
@DisplayName("buildParamsOptionalInt.of → Integerempty → null")
void testBuildParamsOptionalInt() {
Object[] result = buildParams(OptionalInt.of(42), OptionalInt.empty());
assertEquals(2, result.length);
assertEquals(42, result[0]);
assertInstanceOf(Integer.class, result[0]);
assertNull(result[1]);
}
@Test
@DisplayName("buildParamsOptionalLong.of → Longempty → null")
void testBuildParamsOptionalLong() {
Object[] result = buildParams(OptionalLong.of(100L), OptionalLong.empty());
assertEquals(2, result.length);
assertEquals(100L, result[0]);
assertInstanceOf(Long.class, result[0]);
assertNull(result[1]);
}
@Test
@DisplayName("buildParamsOptionalDouble.of → Doubleempty → null")
void testBuildParamsOptionalDouble() {
Object[] result = buildParams(OptionalDouble.of(3.14), OptionalDouble.empty());
assertEquals(2, result.length);
assertEquals(3.14, result[0]);
assertInstanceOf(Double.class, result[0]);
assertNull(result[1]);
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - buildParams混合所有类型
// --------------------------------------------------------------------
@Test
@DisplayName("buildParams混合所有 Optional + 普通类型 + null")
void testBuildParamsMixedAll() {
Object[] result = buildParams(
Optional.of("present"), Optional.empty(),
OptionalInt.of(10), OptionalInt.empty(),
OptionalLong.of(200L), OptionalLong.empty(),
OptionalDouble.of(1.5), OptionalDouble.empty(),
"plain", 999, null);
assertEquals(11, result.length);
assertEquals("present", result[0]);
assertNull(result[1]);
assertEquals(10, result[2]);
assertNull(result[3]);
assertEquals(200L, result[4]);
assertNull(result[5]);
assertEquals(1.5, result[6]);
assertNull(result[7]);
assertEquals("plain", result[8]);
assertEquals(999, result[9]);
assertNull(result[10]);
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - buildBatchParams
// --------------------------------------------------------------------
@Test
@DisplayName("buildBatchParams集合映射为 List<Object[]>,配合 buildParams 使用README 示例风格)")
void testBuildBatchParams() {
List<String[]> data = Arrays.asList(
new String[]{"admin", "123456", "0000"},
new String[]{"user1", "pass1", "0001"},
new String[]{"user2", "pass2", "0002"});
// README 风格: buildBatchParams(collection, item -> buildParams(...))
List<Object[]> result = buildBatchParams(data,
row -> buildParams(row[0], row[1], row[2]));
assertEquals(3, result.size());
assertArrayEquals(new Object[]{"admin", "123456", "0000"}, result.get(0));
assertArrayEquals(new Object[]{"user1", "pass1", "0001"}, result.get(1));
assertArrayEquals(new Object[]{"user2", "pass2", "0002"}, result.get(2));
}
@Test
@DisplayName("buildBatchParams边界情况——空集合 / null collection / null func")
void testBuildBatchParamsBoundary() {
// 空集合返回 Collections.emptyList()
List<Object[]> emptyResult = buildBatchParams(Collections.emptyList(),
(Function<Object, Object[]>) obj -> new Object[]{obj});
assertTrue(emptyResult.isEmpty());
assertSame(Collections.emptyList(), emptyResult);
// null collection 抛异常
assertThrows(Exception.class, () ->
buildBatchParams(null, (Function<Object, Object[]>) obj -> new Object[]{obj}));
// null func 抛异常
assertThrows(Exception.class, () ->
buildBatchParams(Arrays.asList("a", "b"), null));
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
// ====================================================================
// #region - 私有构造器
// --------------------------------------------------------------------
@Test
@DisplayName("私有构造器抛 IllegalStateException")
void testPrivateConstructor() throws Exception {
java.lang.reflect.Constructor<ParamBuilder> ctor =
ParamBuilder.class.getDeclaredConstructor();
ctor.setAccessible(true);
java.lang.reflect.InvocationTargetException ex = assertThrows(
java.lang.reflect.InvocationTargetException.class, ctor::newInstance);
assertInstanceOf(IllegalStateException.class, ex.getCause());
assertEquals("Utility class", ex.getCause().getMessage());
}
// --------------------------------------------------------------------
// #endregion
// ====================================================================
}

View File

@@ -16,9 +16,10 @@ import xyz.zhouxy.jdbc.SimpleJdbcTemplate;
import xyz.zhouxy.jdbc.TransactionException;
/**
* 事务 API 测试:executeTransaction、commitIfTrue。
* 事务 API 测试:通过 {@link xyz.zhouxy.jdbc.TransactionTemplate#execute} 和
* {@link xyz.zhouxy.jdbc.TransactionTemplate#commitIfTrue} 测试事务提交与回滚。
*/
@DisplayName("SimpleJdbcTemplate 事务操作")
@DisplayName("TransactionTemplate 事务操作")
class TransactionTest extends BaseH2Test {
private static final Logger logger = LoggerFactory.getLogger(TransactionTest.class);
@@ -28,14 +29,14 @@ class TransactionTest extends BaseH2Test {
resetDatabase();
}
// ==================== executeTransaction 正常提交 ====================
// ==================== execute 正常提交 ====================
@Test
@DisplayName("executeTransaction:正常提交,数据持久化")
@DisplayName("execute正常提交数据持久化")
void testExecuteTransactionCommit() throws Exception {
SimpleJdbcTemplate template = createTemplate();
template.executeTransaction((JdbcOperations ops) -> {
template.transaction().execute((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username, email, age, balance, active) VALUES (?, ?, ?, ?, ?)",
buildParams("txUser1", "tx1@test.com", 25, 1000L, true));
ops.update("UPDATE users SET balance = ? WHERE username = ?",
@@ -56,10 +57,10 @@ class TransactionTest extends BaseH2Test {
logger.info("事务提交验证通过");
}
// ==================== executeTransaction 异常回滚 ====================
// ==================== execute 异常回滚 ====================
@Test
@DisplayName("executeTransaction:异常回滚,数据恢复原状")
@DisplayName("execute异常回滚数据恢复原状")
void testExecuteTransactionRollback() throws Exception {
SimpleJdbcTemplate template = createTemplate();
@@ -69,7 +70,7 @@ class TransactionTest extends BaseH2Test {
buildParams("alice"), Long.class);
TransactionException ex = assertThrows(TransactionException.class, () ->
template.executeTransaction((JdbcOperations ops) -> {
template.transaction().execute((JdbcOperations ops) -> {
ops.update("UPDATE users SET balance = ? WHERE username = ?",
buildParams(0L, "alice"));
ops.update("INSERT INTO users (username, email) VALUES (?, ?)",
@@ -99,12 +100,12 @@ class TransactionTest extends BaseH2Test {
}
@Test
@DisplayName("executeTransactionSQL 异常触发回滚")
@DisplayName("executeSQL 异常触发回滚")
void testExecuteTransactionSqlExceptionRollback() {
SimpleJdbcTemplate template = createTemplate();
assertThrows(TransactionException.class, () ->
template.executeTransaction((JdbcOperations ops) -> {
template.transaction().execute((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username) VALUES (?)",
buildParams("validUser"));
// 错误的 SQL
@@ -120,14 +121,14 @@ class TransactionTest extends BaseH2Test {
});
}
// ==================== commitIfTrue 返回 true 提交 ====================
// ==================== commitIfTrue返回 true 提交 ====================
@Test
@DisplayName("commitIfTrue返回 true 提交事务")
void testCommitIfTrueCommit() throws Exception {
SimpleJdbcTemplate template = createTemplate();
template.commitIfTrue((JdbcOperations ops) -> {
template.transaction().commitIfTrue((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username, email) VALUES (?, ?)",
buildParams("cftUser", "cft@test.com"));
return true;
@@ -147,7 +148,7 @@ class TransactionTest extends BaseH2Test {
void testCommitIfFalseRollback() throws Exception {
SimpleJdbcTemplate template = createTemplate();
template.commitIfTrue((JdbcOperations ops) -> {
template.transaction().commitIfTrue((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username, email) VALUES (?, ?)",
buildParams("cffUser", "cff@test.com"));
return false;
@@ -168,7 +169,7 @@ class TransactionTest extends BaseH2Test {
SimpleJdbcTemplate template = createTemplate();
assertThrows(TransactionException.class, () ->
template.commitIfTrue((JdbcOperations ops) -> {
template.transaction().commitIfTrue((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username) VALUES (?)",
buildParams("exUser"));
throw new IllegalStateException("条件不满足");
@@ -186,11 +187,11 @@ class TransactionTest extends BaseH2Test {
// ==================== 事务内查询可见性 ====================
@Test
@DisplayName("executeTransaction:事务内可查询到未提交的数据")
@DisplayName("execute事务内可查询到未提交的数据")
void testTransactionVisibility() throws Exception {
SimpleJdbcTemplate template = createTemplate();
template.executeTransaction((JdbcOperations ops) -> {
template.transaction().execute((JdbcOperations ops) -> {
ops.update("INSERT INTO users (username, email) VALUES (?, ?)",
buildParams("visible", "visible@test.com"));
@@ -207,13 +208,13 @@ class TransactionTest extends BaseH2Test {
// ==================== 边界情况 ====================
@Test
@DisplayName("executeTransaction:空操作(无异常)正常提交")
@DisplayName("execute空操作无异常正常提交")
void testExecuteTransactionEmpty() throws Exception {
SimpleJdbcTemplate template = createTemplate();
// 空操作不应抛异常
assertDoesNotThrow(() ->
template.executeTransaction(ops -> { /* no-op */ }));
template.transaction().execute(ops -> { /* no-op */ }));
// 数据应保持不变
int count = template.query("SELECT COUNT(*) FROM users",
@@ -222,12 +223,12 @@ class TransactionTest extends BaseH2Test {
}
@Test
@DisplayName("executeTransactionnull 操作抛异常")
@DisplayName("executenull 操作抛异常")
@SuppressWarnings("null")
void testExecuteTransactionNullOps() {
SimpleJdbcTemplate template = createTemplate();
assertThrows(Exception.class, () ->
template.executeTransaction(null));
template.transaction().execute(null));
}
}

View File

@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static xyz.zhouxy.jdbc.ParamBuilder.buildParams;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@@ -20,6 +21,8 @@ import xyz.zhouxy.jdbc.SimpleJdbcTemplate;
/**
* 更新 API 测试update、updateAndReturnKeys。
*
* <p>内部按 PreparedStatement有参数和 Statement无参数路径组织。</p>
*/
@DisplayName("SimpleJdbcTemplate 更新操作")
class UpdateTest extends BaseH2Test {
@@ -32,6 +35,7 @@ class UpdateTest extends BaseH2Test {
}
// ==================== update ====================
// --- PreparedStatement 路径(有参数) ---
@Test
@DisplayName("updateINSERT 操作返回影响行数 1")
@@ -120,7 +124,59 @@ class UpdateTest extends BaseH2Test {
}
@Test
@DisplayName("updateDELETE 全表")
@DisplayName("update参数中包含 null 元素")
void testUpdateWithNullElement() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
int rows = template.update(
"DELETE FROM users WHERE username = ?",
new Object[]{ null });
// 参数 null 不匹配任何行
assertEquals(0, rows);
}
@Test
@DisplayName("update使用 Instant 类型参数填充 TIMESTAMP 列")
void testUpdateWithInstantParam() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS);
String sql = "INSERT INTO users (username, email, created_at) VALUES (?, ?, ?)";
int rows = template.update(sql,
buildParams("instant_user", "instant@example.com", now));
assertEquals(1, rows);
// 验证存储的值与原始 Instant 一致
java.sql.Timestamp stored = template.query(
"SELECT created_at FROM users WHERE username = ?",
buildParams("instant_user"),
rs -> {
rs.next();
return rs.getTimestamp(1);
});
assertNotNull(stored);
assertEquals(java.sql.Timestamp.from(now), stored);
}
// --- update / Statement 路径(无参数) ---
@Test
@DisplayName("update无参数重载")
void testUpdateNoParams() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
int rows = template.update(
"UPDATE users SET balance = 9999 WHERE username = 'alice'");
assertEquals(1, rows);
}
@Test
@DisplayName("updateDELETE 全表(无参数)")
void testUpdateDeleteAll() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
@@ -136,27 +192,13 @@ class UpdateTest extends BaseH2Test {
}
@Test
@DisplayName("updatenull 参数数组")
void testUpdateWithNullParams() throws SQLException {
@DisplayName("updateparams 为 null走 Statement 路径")
void testUpdateWithParamsNull() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
int rows = template.update(
"DELETE FROM users WHERE username = ?",
new Object[]{ null });
int rows = template.update("DELETE FROM users", (Object[]) null);
// 因为 DELETE ? 中参数 null 不会匹配任何行
assertEquals(0, rows);
}
@Test
@DisplayName("update无参数重载")
void testUpdateNoParams() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
int rows = template.update(
"UPDATE users SET balance = 9999 WHERE username = 'alice'");
assertEquals(1, rows);
assertEquals(5, rows);
}
@Test
@@ -169,6 +211,7 @@ class UpdateTest extends BaseH2Test {
}
// ==================== updateAndReturnKeys ====================
// --- PreparedStatement 路径(有参数) ---
@Test
@DisplayName("updateAndReturnKeysINSERT 返回自增主键")
@@ -204,6 +247,8 @@ class UpdateTest extends BaseH2Test {
assertEquals(2, keys.size());
}
// --- updateAndReturnKeys / Statement 路径(无参数) ---
@Test
@DisplayName("updateAndReturnKeys无参数重载")
void testUpdateAndReturnKeysNoParams() throws SQLException {
@@ -216,4 +261,18 @@ class UpdateTest extends BaseH2Test {
assertEquals(1, keys.size());
assertTrue(keys.get(0) > 0);
}
@Test
@DisplayName("updateAndReturnKeysparams 为 null走 Statement 路径")
void testUpdateAndReturnKeysWithParamsNull() throws SQLException {
SimpleJdbcTemplate template = createTemplate();
RowMapper<Long> rowMapper = (rs, rowNumber) -> rs.getLong(1);
List<Long> keys = template.updateAndReturnKeys(
"INSERT INTO users (username) VALUES ('null_test')",
null, rowMapper);
assertEquals(1, keys.size());
assertTrue(keys.get(0) > 0);
}
}