Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 45f621d31a | |||
| 492be49322 | |||
| 1a308ed30e | |||
| b639daca30 | |||
| 20d10b84ee | |||
| 8e543b40a6 | |||
| 3aff7509eb | |||
| 3ad5718f8c | |||
| 8de546b7a6 | |||
| 9bf44c5494 | |||
| a51fcef845 | |||
| cb9fd4ca75 | |||
| ddddea0519 |
184
README.md
184
README.md
@@ -1,64 +1,126 @@
|
||||
# SimpleJDBC
|
||||
|
||||
对 JDBC 的简单封装。
|
||||
SimpleJDBC 是一个轻量级 JDBC 工具库,提供简洁的 API 用于执行 SQL 查询、更新、批量操作及事务管理,适用于未引入 ORM 框架、直接使用原生 JDBC 的项目。
|
||||
|
||||
之前遇到的一个老项目,没有引入任何 ORM 框架,对数据库的操作几乎都在写原生 JDBC。故自己写了几个工具类,对 JDBC 进行简单封装。
|
||||
## 1. 快速开始
|
||||
|
||||
## 查询
|
||||
**要求 JDK 8+。**
|
||||
|
||||
### 查询方法
|
||||
Maven 依赖:
|
||||
|
||||
- `query`:**最基础的查询方法**。可使用 `ResultHandler` 将查询结果映射为 Java 对象。
|
||||
- `queryList`:**查询列表**。可使用 `RowMapper` 将结果的每一行数据映射为 Java 对象,返回列表。
|
||||
- `queryFirst`:**查询,并获取第一行数据**。一般可以结合 `LIMIT 1` 使用。可使用 `RowMapper` 将结果的第一行数据映射为 Java 对象,返回 `Optional`。
|
||||
- `queryBoolean`:**获取第一行数据的第一个字段,并转换为布尔类型**。如果结果为空,则返回 `false`。
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>xyz.zhouxy.jdbc</groupId>
|
||||
<artifactId>simple-jdbc</artifactId>
|
||||
<version>${simple-jdbc.version}</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 结果映射
|
||||
> 本项目基于 **Apache License 2.0** 开源。
|
||||
|
||||
- `ResultHandler` 用于处理查询结果,自定义逻辑将完整的 `ResultSet` 映射为 Java 对象。 *结果可以是任意类型(包括集合)。*
|
||||
- `RowMapper` 用于将 `ResultSet` 中的一行数据映射为 Java 对象。
|
||||
- `RowMapper#HASH_MAP_MAPPER`:将 `ResultSet` 中的一行数据映射为 `HashMap`。
|
||||
- `RowMapper#beanRowMapper`:返回将 `ResultSet` 转换为 Java Bean 的默认实现。
|
||||
## 2. 查询
|
||||
|
||||
## 更新
|
||||
### 2.1 查询方法
|
||||
|
||||
- `int update`:**执行 DML**,包括 `INSERT`、`UPDATE`、`DELETE` 等。返回受影响行数。
|
||||
- `<T> List<T> update`:**执行 DML**,自动生成的字段将使用 `rowMapper` 进行映射,并返回列表。
|
||||
- `List<int[]> batchUpdate`:**分批次执行 DML**,返回分批执行的结果。
|
||||
所有查询方法均使用 `Object[]` 作为参数,并提供了无参便捷重载(适用于不含占位符的 SQL)。
|
||||
|
||||
## 事务
|
||||
| 方法 | 说明 |
|
||||
|---|---|
|
||||
| `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` |
|
||||
| `queryFirst(sql, params, Class)` | 查询第一行第一列,返回 `Optional<T>` |
|
||||
| `queryFirst(sql, params)` | 查询第一行,返回 `Optional<Map<String, Object>>` |
|
||||
| `queryBoolean(sql, params)` | 查询第一行第一列并转为 boolean,结果为空返回 `false` |
|
||||
|
||||
- `executeTransaction`:**执行事务**。传入一个 `ThrowingConsumer` 函数,入参是一个 `JdbcOperations` 对象,在 `ThrowingConsumer` 内使用该入参执行 jdbc 操作。如果 `ThrowingConsumer` 内部有异常抛出,这些操作将被回滚。
|
||||
> 以上方法均有不含 `params` 的便捷重载,例如 `queryList(sql, rowMapper)`、`queryFirst(sql, Class)` 等,适用于无参数 SQL。
|
||||
|
||||
- `commitIfTrue`:**执行事务**。传入一个 `ThrowingPredicate` 函数,入参是一个 `JdbcOperations` 对象,在 `ThrowingPredicate` 内使用该入参执行 jdbc 操作。如果`ThrowingPredicate` 返回 `true`,则提交事务;如果返回 `false` 或有异常抛出,则回滚这些操作。
|
||||
### 2.2 结果映射
|
||||
|
||||
## 参数构建
|
||||
- **`ResultHandler`**:处理完整的 `ResultSet`,自定义逻辑将结果映射为任意类型(包括集合)。
|
||||
- **`RowMapper`**:将 `ResultSet` 中的一行数据映射为 Java 对象。
|
||||
- `RowMapper.HASH_MAP_MAPPER`:每行映射为 `HashMap<String, Object>`。
|
||||
- `RowMapper.beanRowMapper(Class)`:默认的 Bean 映射,属性名(小驼峰) ↔ 列名(小写蛇形)。
|
||||
- `RowMapper.beanRowMapper(Class, Map<String, String>)`:自定义属性名与列名映射的 Bean 映射。
|
||||
|
||||
此项目中的所有查询和更新的方法,都**不使用可变长入参**,避免强行将 SQL 语句的参数列表放在最后,也避免和数组发生歧义。
|
||||
## 3. 更新
|
||||
|
||||
### 构建参数列表
|
||||
所有更新方法同样提供了无参便捷重载。
|
||||
|
||||
可使用 `ParamBuilder#buildParams` 构建 `Object[]` 数组作为 SQL 的参数列表。该方法会自动将 `Optional` 中的值“拆”出来。
|
||||
| 方法 | 说明 |
|
||||
|---|---|
|
||||
| `update(sql, params)` | 执行 DML(INSERT / UPDATE / DELETE),返回受影响行数 |
|
||||
| `updateAndReturnKeys(sql, params, rowMapper)` | 执行 DML 并返回自动生成的键,通过 `RowMapper` 映射 |
|
||||
| `batchUpdate(sql, params, batchSize)` | 分批执行 DML,遇错即中断 |
|
||||
| `batchUpdate(sql, params, batchSize, quietly)` | 分批执行 DML;`quietly=true` 遇错不中断,全部执行完毕 |
|
||||
|
||||
### 批量构建参数列表
|
||||
### BatchUpdateResult
|
||||
|
||||
使用 `ParamBuilder#buildBatchParams`,将使用传入的函数,将集合中的每一个元素转为 `Object[]`,并返回一个 `List<Object[]>`。
|
||||
`batchUpdate` 返回 `BatchUpdateResult`,包含:
|
||||
|
||||
## 示例
|
||||
- `getStatus()`:批次状态(`SUCCESS` / `COMPLETED_WITH_ERRORS` / `INTERRUPTED`)
|
||||
- `getTotal()`:总数据量
|
||||
- `getBatchCount()`:总批次数
|
||||
- `getSuccessBatchCount()` / `getErrorBatchCount()`:成功/失败批次数
|
||||
- `getBatchUpdateErrorInfo(batchIndex)`:获取指定批次的错误详情
|
||||
|
||||
## 4. 事务
|
||||
|
||||
通过 `TransactionTemplate` 管理事务,可直接创建或通过 `SimpleJdbcTemplate.transaction()` 获取。
|
||||
|
||||
- **`execute(consumer)`**:执行事务。传入 `ThrowingConsumer<JdbcOperations>`,若内部无异常则提交,有异常则回滚。
|
||||
- **`commitIfTrue(predicate)`**:执行事务。传入 `ThrowingPredicate<JdbcOperations>`,返回 `true` 提交,返回 `false` 或抛异常则回滚。
|
||||
|
||||
## 5. 参数构建
|
||||
|
||||
此项目中所有方法都**不使用可变长参数**,避免强制将参数列表放在 SQL 语句末尾,也避免与数组产生歧义。
|
||||
|
||||
### 5.1 构建参数列表
|
||||
|
||||
使用 `ParamBuilder.buildParams(...)` 构建 `Object[]` 作为 SQL 参数。该方法会自动将 `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}
|
||||
```
|
||||
|
||||
### 5.2 批量构建参数列表
|
||||
|
||||
使用 `ParamBuilder.buildBatchParams(collection, func)` 将集合中每个元素转为 `Object[]`,返回 `List<Object[]>`。
|
||||
|
||||
```java
|
||||
import static xyz.zhouxy.jdbc.ParamBuilder.buildBatchParams;
|
||||
import static xyz.zhouxy.jdbc.ParamBuilder.buildParams;
|
||||
|
||||
buildBatchParams(accountList, account -> buildParams(
|
||||
account.getUsername(),
|
||||
account.getPassword(),
|
||||
account.getOrgNo()
|
||||
));
|
||||
```
|
||||
|
||||
## 6. 示例
|
||||
|
||||
创建 `SimpleJdbcTemplate` 对象:
|
||||
|
||||
创建 SimpleJdbcTemplate 对象
|
||||
```java
|
||||
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
|
||||
```
|
||||
|
||||
查询
|
||||
### 6.1 查询
|
||||
|
||||
```java
|
||||
// 查询(使用 ResultHandler 处理全部结果)
|
||||
List<Account> list = jdbcTemplate.query(
|
||||
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"),
|
||||
@@ -79,14 +141,16 @@ List<String> usernames = jdbcTemplate.queryList(
|
||||
buildParams("admin%", "0000"),
|
||||
String.class
|
||||
);
|
||||
|
||||
// 查询列表(使用 DefaultBeanRowMapper 进行映射)
|
||||
List<Account> list = jdbcTemplate.queryList(
|
||||
List<Account> accounts = 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(
|
||||
List<Account> accounts = jdbcTemplate.queryList(
|
||||
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
|
||||
buildParams("admin%", "0000"),
|
||||
(rs, rowNum) -> new Account(
|
||||
@@ -109,17 +173,25 @@ Optional<Account> account = jdbcTemplate.queryFirst(
|
||||
rs.getString("password"),
|
||||
rs.getString("org_no"),
|
||||
rs.getTimestamp("create_time"),
|
||||
rs.getTimestamp("update_time")
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// 查询 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)
|
||||
);
|
||||
|
||||
// 无参数 SQL 可直接省略 params
|
||||
List<Account> allAccounts = jdbcTemplate.queryList(
|
||||
"SELECT * FROM account WHERE deleted = 0",
|
||||
RowMapper.beanRowMapper(Account.class)
|
||||
);
|
||||
```
|
||||
|
||||
更新
|
||||
### 6.2 更新
|
||||
|
||||
```java
|
||||
// 执行 DML
|
||||
int affectedRows = jdbcTemplate.update(
|
||||
@@ -138,8 +210,10 @@ List<Pair<Long, LocalDateTime>> keys = jdbcTemplate.updateAndReturnKeys(
|
||||
);
|
||||
```
|
||||
|
||||
批量更新
|
||||
### 6.3 批量更新
|
||||
|
||||
```java
|
||||
// 默认:遇错即中断
|
||||
BatchUpdateResult result = jdbcTemplate.batchUpdate(
|
||||
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
|
||||
buildBatchParams(accountList, account -> buildParams(
|
||||
@@ -147,21 +221,43 @@ BatchUpdateResult result = jdbcTemplate.batchUpdate(
|
||||
account.getPassword(),
|
||||
account.getOrgNo()
|
||||
)),
|
||||
100 // 每100条数据一个批次
|
||||
100 // 每 100 条数据一个批次
|
||||
);
|
||||
|
||||
// 静默模式:遇错不中断,全部执行完毕后统一检查结果
|
||||
BatchUpdateResult result = jdbcTemplate.batchUpdate(
|
||||
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
|
||||
buildBatchParams(accountList, account -> buildParams(
|
||||
account.getUsername(),
|
||||
account.getPassword(),
|
||||
account.getOrgNo()
|
||||
)),
|
||||
100,
|
||||
true // quietly = true,遇错不中断
|
||||
);
|
||||
|
||||
// 检查批量更新结果
|
||||
if (result.getStatus() == BatchUpdateStatus.COMPLETED_WITH_ERRORS) {
|
||||
for (int idx : result.getErrorBatchIndexes()) {
|
||||
BatchUpdateErrorInfo err = result.getBatchUpdateErrorInfo(idx);
|
||||
System.err.println("批次 " + idx + " 失败: " + err.getCause().getMessage());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
事务
|
||||
### 6.4 事务
|
||||
|
||||
```java
|
||||
jdbcTemplate.executeTransaction(jdbc -> {
|
||||
jdbcTemplate.transaction().execute(jdbc -> {
|
||||
...
|
||||
jdbc.update(...);
|
||||
...
|
||||
jdbc.update(...);
|
||||
...
|
||||
// 无异常则自动提交
|
||||
});
|
||||
|
||||
jdbcTemplate.commitIfTrue(jdbc -> {
|
||||
jdbcTemplate.transaction().commitIfTrue(jdbc -> {
|
||||
...
|
||||
jdbc.update(...);
|
||||
...
|
||||
@@ -182,4 +278,8 @@ jdbcTemplate.commitIfTrue(jdbc -> {
|
||||
});
|
||||
```
|
||||
|
||||
>**!!!本项目不比成熟的工具,如若使用请自行承担风险。建议仅作为 JDBC 的学习参考。**
|
||||
> **!!!本项目不比成熟的工具,如若使用请自行承担风险。**
|
||||
>
|
||||
> - **线程安全**:`SimpleJdbcTemplate` 无内部状态,线程安全。但所依赖的 `DataSource` 需自行保证线程安全。
|
||||
> - **连接管理**:每次操作自动从 `DataSource` 获取连接并在操作完成后关闭,无需手动管理。
|
||||
> - **适用场景**:不适合高并发或大数据量场景,建议仅用于学习参考或小型项目。
|
||||
|
||||
2
pom.xml
2
pom.xml
@@ -5,7 +5,7 @@
|
||||
|
||||
<groupId>xyz.zhouxy.jdbc</groupId>
|
||||
<artifactId>simple-jdbc</artifactId>
|
||||
<version>1.0.0-RC1</version>
|
||||
<version>1.0.0-RC2</version>
|
||||
|
||||
<name>Simple JDBC</name>
|
||||
<description>对 JDBC 的简单封装。</description>
|
||||
|
||||
@@ -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()
|
||||
+ "}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 ["
|
||||
|
||||
@@ -230,20 +230,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 +266,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;
|
||||
|
||||
@@ -27,7 +27,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,11 +50,7 @@ public class ParamBuilder {
|
||||
if (ArrayTools.isEmpty(params)) {
|
||||
return EMPTY_OBJECT_ARRAY;
|
||||
}
|
||||
return buildParamsFromStream(Arrays.stream(params));
|
||||
}
|
||||
|
||||
private static Object[] buildParamsFromStream(Stream<?> stream) {
|
||||
return stream
|
||||
return Arrays.stream(params)
|
||||
.map(param -> {
|
||||
if (param instanceof Optional) {
|
||||
return OptionalTools.orElseNull((Optional<?>) param);
|
||||
|
||||
@@ -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
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
271
src/main/java/xyz/zhouxy/jdbc/TransactionTemplate.java
Normal file
271
src/main/java/xyz/zhouxy/jdbc/TransactionTemplate.java
Normal 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
|
||||
}
|
||||
227
src/test/java/xyz/zhouxy/jdbc/test/ParamBuilderTest.java
Normal file
227
src/test/java/xyz/zhouxy/jdbc/test/ParamBuilderTest.java
Normal 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 - buildParams:Optional<?>
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("buildParams:Optional.of 拆箱为值,Optional.empty 拆箱为 null(README 示例)")
|
||||
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 - buildParams:OptionalInt / OptionalLong / OptionalDouble
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("buildParams:OptionalInt.of → Integer,empty → 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("buildParams:OptionalLong.of → Long,empty → 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("buildParams:OptionalDouble.of → Double,empty → 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
|
||||
// ====================================================================
|
||||
}
|
||||
@@ -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("executeTransaction:SQL 异常触发回滚")
|
||||
@DisplayName("execute:SQL 异常触发回滚")
|
||||
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("executeTransaction:null 操作抛异常")
|
||||
@DisplayName("execute:null 操作抛异常")
|
||||
@SuppressWarnings("null")
|
||||
void testExecuteTransactionNullOps() {
|
||||
SimpleJdbcTemplate template = createTemplate();
|
||||
|
||||
assertThrows(Exception.class, () ->
|
||||
template.executeTransaction(null));
|
||||
template.transaction().execute(null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -168,6 +169,32 @@ class UpdateTest extends BaseH2Test {
|
||||
template.update("UPDAT users SET x = 1"));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
// ==================== updateAndReturnKeys ====================
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user