forked from plusone/simple-jdbc
Compare commits
1 Commits
dev
...
1f0da1fdd0
Author | SHA1 | Date | |
---|---|---|---|
1f0da1fdd0 |
@@ -13,6 +13,3 @@ insert_final_newline = true
|
|||||||
|
|
||||||
[*.sql]
|
[*.sql]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
|
||||||
[*.md]
|
|
||||||
indent_size = 2
|
|
||||||
|
5
.gitignore
vendored
5
.gitignore
vendored
@@ -4,7 +4,10 @@ target/
|
|||||||
!**/src/test/**/target/
|
!**/src/test/**/target/
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
### IntelliJ IDEA ###
|
||||||
.idea/
|
.idea/modules.xml
|
||||||
|
.idea/jarRepositories.xml
|
||||||
|
.idea/compiler.xml
|
||||||
|
.idea/libraries/
|
||||||
*.iws
|
*.iws
|
||||||
*.iml
|
*.iml
|
||||||
*.ipr
|
*.ipr
|
||||||
|
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# 默认忽略的文件
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
7
.idea/encodings.xml
generated
Normal file
7
.idea/encodings.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Encoding">
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||||
|
</component>
|
||||||
|
</project>
|
6
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
6
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<profile version="1.0">
|
||||||
|
<option name="myName" value="Project Default" />
|
||||||
|
<inspection_tool class="NonSerializableWithSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||||
|
</profile>
|
||||||
|
</component>
|
14
.idea/misc.xml
generated
Normal file
14
.idea/misc.xml
generated
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="MavenProjectsManager">
|
||||||
|
<option name="originalFiles">
|
||||||
|
<list>
|
||||||
|
<option value="$PROJECT_DIR$/pom.xml" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
|
</component>
|
||||||
|
</project>
|
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
179
README.md
179
README.md
@@ -1,181 +1,6 @@
|
|||||||
# SimpleJDBC
|
# SimpleJDBC
|
||||||
|
|
||||||
对 JDBC 的简单封装。
|
对 JDBC 的简单封装。
|
||||||
|
|
||||||
之前遇到的一个老项目,没有引入任何 ORM 框架,对数据库的操作几乎都在写原生 JDBC。故自己写了几个工具类,对 JDBC 进行简单封装。
|
之前遇到的一个老项目,没有引入任何 ORM 框架,使用的 JDK7 明明支持泛型,所依赖的 spring-jdbc 居然是没有泛型的远古版本,该项目又不允许随意添加依赖,对数据库的操作几乎都在写原生 JDBC。故自己写了几个工具类,对 JDBC 进行简单封装,后来逐渐改进完善。
|
||||||
|
|
||||||
## 查询
|
本项目不比成熟的工具,如若使用请自行承担风险。建议仅作为 JDBC 的学习参考。
|
||||||
|
|
||||||
### 查询方法
|
|
||||||
|
|
||||||
- `query`:**最基础的查询方法**。可使用 `ResultHandler` 将查询结果映射为 Java 对象。
|
|
||||||
- `queryList`:**查询列表**。可使用 `RowMapper` 将结果的每一行数据映射为 Java 对象,返回列表。
|
|
||||||
- `queryFirst`:**查询,并获取第一行数据**。一般可以结合 `LIMIT 1` 使用。可使用 `RowMapper` 将结果的第一行数据映射为 Java 对象,返回 `Optional`。
|
|
||||||
- `queryFirstXXX`:**查询,并获取第一行数据的第一个字段**,并转换为对应类型,返回对应的类型的 `Optional`。
|
|
||||||
- `queryAsBoolean`:**查询,并获取第一行数据的第一个字段**,并转换为布尔类型。如果结果为空,则返回 `false`。
|
|
||||||
|
|
||||||
### 结果映射
|
|
||||||
|
|
||||||
- `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**,返回每个批次的每条 SQL 语句影响的行数。
|
|
||||||
- `List<int[]> batchUpdateAndIgnoreException`:**分批次执行 DML,如果某个批次出现异常,继续执行下一个批次**。返回每个批次的每条 SQL 语句影响的行数。
|
|
||||||
|
|
||||||
## 事务
|
|
||||||
|
|
||||||
- `executeTransaction`:**执行事务**。传入一个 `ThrowingConsumer` 函数,入参是一个 `JdbcExecutor` 对象,在 `ThrowingConsumer` 内使用该入参执行 jdbc 操作。如果 `ThrowingConsumer` 内部有异常抛出,这些操作将被回滚。
|
|
||||||
|
|
||||||
- `commitIfTrue`:**执行事务**。传入一个 `ThrowingPredicate` 函数,入参是一个 `JdbcExecutor` 对象,在 `ThrowingPredicate` 内使用该入参执行 jdbc 操作。如果`ThrowingPredicate` 返回 `true`,则提交事务;如果返回 `false` 或有异常抛出,则回滚这些操作。
|
|
||||||
|
|
||||||
## 参数构建
|
|
||||||
|
|
||||||
此项目中的所有查询和更新的方法,都**不使用可变长入参**,避免强行将 SQL 语句的参数列表放在最后,也避免和数组发生歧义。
|
|
||||||
|
|
||||||
### 构建参数列表
|
|
||||||
|
|
||||||
可使用 `ParamBuilder#buildParams` 构建 `Object[]` 数组作为 SQL 的参数列表。该方法会自动将 `Optional` 中的值“拆”出来。
|
|
||||||
|
|
||||||
### 批量构建参数列表
|
|
||||||
|
|
||||||
使用 `ParamBuilder#buildBatchParams`,将使用传入的函数,将集合中的每一个元素转为 `Object[]`,并返回一个 `List<Object[]>`。
|
|
||||||
|
|
||||||
## 示例
|
|
||||||
|
|
||||||
创建 SimpleJdbcTemplate 对象
|
|
||||||
```java
|
|
||||||
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
|
|
||||||
```
|
|
||||||
|
|
||||||
查询
|
|
||||||
```java
|
|
||||||
// 查询
|
|
||||||
List<Account> list = jdbcTemplate.query(
|
|
||||||
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
|
|
||||||
buildParams("admin%", "0000"),
|
|
||||||
rs -> {
|
|
||||||
List<T> result = new ArrayList<>();
|
|
||||||
while (rs.next()) {
|
|
||||||
result.add(new Account(
|
|
||||||
rs.getLong("id"),
|
|
||||||
rs.getString("username"),
|
|
||||||
rs.getString("password"),
|
|
||||||
rs.getString("org_no"),
|
|
||||||
rs.getTimestamp("create_time"),
|
|
||||||
rs.getTimestamp("update_time")
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// 查询列表
|
|
||||||
List<Account> list = jdbcTemplate.queryList(
|
|
||||||
"SELECT * FROM account WHERE deleted = 0 AND username LIKE ? AND org_no = ?",
|
|
||||||
buildParams("admin%", "0000"),
|
|
||||||
(rs, rowNum) -> new Account(
|
|
||||||
rs.getLong("id"),
|
|
||||||
rs.getString("username"),
|
|
||||||
rs.getString("password"),
|
|
||||||
rs.getString("org_no"),
|
|
||||||
rs.getTimestamp("create_time"),
|
|
||||||
rs.getTimestamp("update_time")
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
// 查询一行数据
|
|
||||||
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"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
// 查询一行数据,并获取第一个字段
|
|
||||||
OptionalInt age = jdbcTemplate.queryFirstInt(
|
|
||||||
"SELECT age FROM view_account WHERE deleted = 0 AND id = ?",
|
|
||||||
buildParams(10000L)
|
|
||||||
);
|
|
||||||
|
|
||||||
// 查询 boolean
|
|
||||||
boolean exists = jdbcTemplate.queryAsBoolean(
|
|
||||||
"SELECT EXISTS(SELECT 1 FROM account WHERE deleted = 0 AND id = ? LIMIT 1)",
|
|
||||||
buildParams(10000L)
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
更新
|
|
||||||
```java
|
|
||||||
// 执行 DML
|
|
||||||
int affectedRows = jdbcTemplate.update(
|
|
||||||
"UPDATE account SET deleted = 1 WHERE id = ?",
|
|
||||||
buildParams(10000L)
|
|
||||||
);
|
|
||||||
|
|
||||||
// 执行 DML,并获取生成的主键
|
|
||||||
List<Pair<Long, LocalDateTime>> keys = jdbcTemplate.update(
|
|
||||||
"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)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
批量更新
|
|
||||||
```java
|
|
||||||
jdbcTemplate.batchUpdate(
|
|
||||||
"INSERT INTO account (username, password, org_no) VALUES (?, ?, ?)",
|
|
||||||
buildBatchParams(accountList, account -> buildParams(
|
|
||||||
account.getUsername(),
|
|
||||||
account.getPassword(),
|
|
||||||
account.getOrgNo()
|
|
||||||
)),
|
|
||||||
100 // 每100条数据一个批次
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
事务
|
|
||||||
```java
|
|
||||||
jdbcTemplate.executeTransaction(jdbc -> {
|
|
||||||
...
|
|
||||||
jdbc.update(...);
|
|
||||||
...
|
|
||||||
jdbc.update(...);
|
|
||||||
...
|
|
||||||
});
|
|
||||||
|
|
||||||
jdbcTemplate.commitIfTrue(jdbc -> {
|
|
||||||
...
|
|
||||||
jdbc.update(...);
|
|
||||||
...
|
|
||||||
if (...) {
|
|
||||||
// 中断操作并回滚
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
...
|
|
||||||
if (...) {
|
|
||||||
// 某些条件下提前结束并提交事务
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
...
|
|
||||||
jdbc.update(...);
|
|
||||||
...
|
|
||||||
// 提交事务
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
>**!!!本项目不比成熟的工具,如若使用请自行承担风险。建议仅作为 JDBC 的学习参考。**
|
|
||||||
|
@@ -48,7 +48,7 @@ import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
|
|||||||
* <b>NOTE: 使用反射获取类型信息,也是使用反射调用无参构造器和 {@code setter} 方法。
|
* <b>NOTE: 使用反射获取类型信息,也是使用反射调用无参构造器和 {@code setter} 方法。
|
||||||
* 实际使用中还是建议针对目标类型自定义 {@link RowMapper}。</b>
|
* 实际使用中还是建议针对目标类型自定义 {@link RowMapper}。</b>
|
||||||
* </p>
|
* </p>
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
public class DefaultBeanRowMapper<T> implements RowMapper<T> {
|
public class DefaultBeanRowMapper<T> implements RowMapper<T> {
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2024-2025 the original author or authors.
|
* Copyright 2024 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -43,7 +43,7 @@ import xyz.zhouxy.plusone.commons.util.AssertTools;
|
|||||||
* 提供静态方法,封装 JDBC 基础操作
|
* 提供静态方法,封装 JDBC 基础操作
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
class JdbcOperationSupport {
|
class JdbcOperationSupport {
|
||||||
|
@@ -1,19 +1,3 @@
|
|||||||
/*
|
|
||||||
* Copyright 2024-2025 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package xyz.zhouxy.jdbc;
|
package xyz.zhouxy.jdbc;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
@@ -36,7 +20,7 @@ import javax.annotation.Nullable;
|
|||||||
* 定义 JdbcTemplate 的 API
|
* 定义 JdbcTemplate 的 API
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
interface JdbcOperations {
|
interface JdbcOperations {
|
||||||
|
@@ -41,7 +41,7 @@ import xyz.zhouxy.plusone.commons.util.OptionalTools;
|
|||||||
* JDBC 参数构造器,将数据转换为 {@code Object[]} 类型,以传给 {@link PreparedStatement}
|
* JDBC 参数构造器,将数据转换为 {@code Object[]} 类型,以传给 {@link PreparedStatement}
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
public class ParamBuilder {
|
public class ParamBuilder {
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2024-2025 the original author or authors.
|
* Copyright 2024 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -26,7 +26,7 @@ import java.sql.SQLException;
|
|||||||
* 处理 {@link ResultSet}
|
* 处理 {@link ResultSet}
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2022-2025 the original author or authors.
|
* Copyright 2022-2024 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -29,7 +29,7 @@ import java.util.Map;
|
|||||||
* {@link ResultSet} 中每一行数据的处理逻辑。
|
* {@link ResultSet} 中每一行数据的处理逻辑。
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2022-2025 the original author or authors.
|
* Copyright 2022-2024 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -43,7 +43,7 @@ import xyz.zhouxy.plusone.commons.util.OptionalTools;
|
|||||||
* 对 JDBC 的简单封装,方便数据库操作,支持事务,支持批量操作,支持自定义结果集映射
|
* 对 JDBC 的简单封装,方便数据库操作,支持事务,支持批量操作,支持自定义结果集映射
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @author ZhouXY108 <luquanlion@outlook.com>
|
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
|
||||||
* @since 1.0.0
|
* @since 1.0.0
|
||||||
*/
|
*/
|
||||||
public class SimpleJdbcTemplate implements JdbcOperations {
|
public class SimpleJdbcTemplate implements JdbcOperations {
|
||||||
|
@@ -1,10 +1,10 @@
|
|||||||
CREATE TABLE sys_account (
|
CREATE TABLE sys_account (
|
||||||
`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY
|
||||||
, `username` VARCHAR(255) NOT NULL
|
,username VARCHAR(255) NOT NULL
|
||||||
, `account_status` VARCHAR(2) NOT NULL
|
,account_status VARCHAR(2) NOT NULL
|
||||||
, `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
,create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
, `created_by` BIGINT NOT NULL
|
,created_by BIGINT NOT NULL
|
||||||
, `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
,update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
, `updated_by` BIGINT DEFAULT NULL
|
,updated_by BIGINT DEFAULT NULL
|
||||||
, `version` BIGINT NOT NULL DEFAULT 0
|
,version BIGINT NOT NULL DEFAULT 0
|
||||||
)
|
)
|
||||||
|
Reference in New Issue
Block a user