1
mirror of https://github.com/CarmJos/EasySQL.git synced 2026-06-14 03:15:55 +08:00

Compare commits

..

42 Commits

Author SHA1 Message Date
carm 5f13b9319d [v0.2.6] 版本更新
- [U] 优化 ConditionalBuilder 的使用方式。
- [A] 为 TableQueryBuilder 添加分表查询limit方法。
- [A] 添加 SQLFunction 类,用于对SQL结果直接进行处理,且不需要在方法内处理异常,交由 ExceptionHandler 进行处理。
2022-01-08 00:55:31 +08:00
carm 5601d1288c [v0.2.6] 版本更新
- [U] 优化 ConditionalBuilder 的使用方式。
- [A] 为 TableQueryBuilder 添加分表查询limit方法。
2022-01-07 23:01:44 +08:00
carm 50b36d8430 [v0.2.5] 打包时不再对slf4j-api进行relocation 2022-01-06 14:39:28 +08:00
carm cd60bf256e 添加依赖地址 2022-01-05 05:09:49 +08:00
carm ebe68befee 添加依赖地址 2022-01-05 04:59:02 +08:00
carm 594413e13b 添加依赖地址 2022-01-05 04:56:57 +08:00
carm df94272c73 [v0.2.4] 依赖relocation并添加Optional标签 2022-01-05 02:32:09 +08:00
carm ab986e9526 [v0.2.3] 添加默认的终止manager方法,并支持强制关闭活动链接。 2021-12-23 15:17:12 +08:00
carm 3f3b7bf4a5 添加代码折叠 2021-12-20 19:09:57 +08:00
carm c69695c16d Merge remote-tracking branch 'origin/master' 2021-12-20 19:08:28 +08:00
carm 02aad28715 添加代码折叠 2021-12-20 19:07:04 +08:00
carm b423000fe5 [U] 使用SonarCloud分析 2021-12-20 18:41:25 +08:00
carm cf356f2492 [U] 使用 SonarCloud 分析。 2021-12-20 18:40:29 +08:00
carm 4775c335d5 [v0.2.2] 版本优化
- `[F]` 修复部分类的使用异常问题
- `[F]` 修复 SQLUpdateBatchAction 中 getSQLContent 方法返回内容不正确导致的其他方法一并出现异常的问题。
- `[U]` 修改 SQLUpdateBatchAction 的默认异常处理器。
- `[F]` 修复 PreparedSQLBatchUpdateActionImpl 异常继承导致的无法使用的问题。
2021-12-19 23:53:35 +08:00
carm 84c35eb481 [v0.2.2] 版本优化
- `[F]` 修复部分类的使用异常问题
- `[F]` 修复 SQLUpdateBatchAction 中 getSQLContent 方法返回内容不正确导致的其他方法一并出现异常的问题。
- `[U]` 修改 SQLUpdateBatchAction 的默认异常处理器。
- `[F]` 修复 PreparedSQLBatchUpdateActionImpl 异常继承导致的无法使用的问题。
2021-12-19 23:47:48 +08:00
carm d30b6b9ab2 添加gpg配置 2021-12-15 20:11:57 +08:00
carm f70f73daf2 Merge remote-tracking branch 'origin/master' 2021-12-15 20:08:33 +08:00
carm 4a7c11ef13 添加SCM配置 2021-12-15 20:08:16 +08:00
carm 427aca95ca Create codacy-analysis.yml 2021-12-15 17:07:49 +08:00
carm 2b86d9234a [v0.2.1-fix] 修改javadoc为中文版本 2021-12-14 20:33:24 +08:00
carm 139d213160 [v0.2.1-fix] 补全缺失的javadoc 2021-12-14 20:23:51 +08:00
carm ebc96e5176 [v0.2.1-fix] 补全缺失的javadoc 2021-12-14 20:19:04 +08:00
carm 7621c86495 [v0.2.1-fix] 修改Javadoc 2021-12-14 20:08:54 +08:00
carm 95182748ef [v0.2.1-fix] 修改Java版本 2021-12-14 20:03:47 +08:00
carm b22dba58d9 [v0.2.1] 版本更新
1. 补充演示代码与部分关键内容的Javadoc
2. 自动部署包含连接池的版本,方便打包使用。
3. 修改了部分代码的逻辑。
2021-12-14 19:56:21 +08:00
carm 8ccf977345 自动部署含连接池版本 2021-12-14 19:53:09 +08:00
carm ac1a9082c7 修改document位置 2021-12-14 19:51:41 +08:00
carm f0650ea720 补充部分JavaDoc 2021-12-14 19:47:35 +08:00
carm 76476a8f9f Merge pull request #1 from MociLSeng/master
master
2021-12-14 19:25:47 +08:00
LSeng cbddc426d2 补充介绍 2021-12-14 18:30:27 +08:00
carm 22c067990b 添加一个同步插入返回ID的方法 2021-12-14 17:30:51 +08:00
carm 2d384bdd15 修改代码演示的位置 2021-12-14 17:24:45 +08:00
carm 85d2ee8984 修改代码示例的注释 2021-12-14 16:25:25 +08:00
carm 7669257028 添加version地址 2021-12-14 16:16:18 +08:00
carm bc00330eef 添加version地址 2021-12-14 16:14:53 +08:00
carm d7db2fbb52 实装 executeAsync 功能,修改异常处理方式,提供action方便获取相关信息。 2021-12-14 16:11:22 +08:00
carm 6de493afbc 修改实例代码 2021-12-14 16:09:55 +08:00
carm 2ecc442bd9 修改Javadoc地址 2021-12-14 06:22:52 +08:00
carm ec2dab31ab 添加Javadoc地址 2021-12-14 06:21:26 +08:00
carm 315a591375 修改部署地址 2021-12-14 06:12:48 +08:00
carm cfac4e2ec6 修改 JAVADOC-README.md 的路径 2021-12-14 06:11:21 +08:00
carm 0f94204b6a 修改javadoc生成方式 2021-12-14 06:03:44 +08:00
58 changed files with 1221 additions and 314 deletions
+9
View File
@@ -0,0 +1,9 @@
# EasySQL Javadoc
基于 [Github Pages](https://pages.github.com/) 搭建,请访问 [JavaDoc](https://carmjos.github.io/EasySQL) 。
## 如何实现?
若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/)
可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。
+4 -4
View File
@@ -12,8 +12,8 @@ assignees: ''
**问题来源** **问题来源**
描述一下通过哪些操作才发现的问题,如: 描述一下通过哪些操作才发现的问题,如:
1. 打开 '...' 1. 使用了 '...'
2. 点击了 '....' 2. 输入了 '....'
3. 出现了报错 '....' 3. 出现了报错 '....'
**预期结果**(可选) **预期结果**(可选)
@@ -23,8 +23,8 @@ assignees: ''
如果有报错或输出,请提供截图。 如果有报错或输出,请提供截图。
**操作环境** **操作环境**
请在后台输入 `version` 并复制相关输出。 - 系统环境: `Windows 10` / `Ubuntu` / `...`
- Java版本: `JDK11` / `OPENJDK8` / `JRE8` / `...`
**其他补充** **其他补充**
如有其他补充,可以在这里描述。 如有其他补充,可以在这里描述。
+54
View File
@@ -0,0 +1,54 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow checks out code, performs a Codacy security scan
# and integrates the results with the
# GitHub Advanced Security code scanning feature. For more information on
# the Codacy security scan action usage and parameters, see
# https://github.com/codacy/codacy-analysis-cli-action.
# For more information on Codacy Analysis CLI in general, see
# https://github.com/codacy/codacy-analysis-cli.
name: Codacy Security Scan
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '27 16 * * 5'
jobs:
codacy-security-scan:
name: Codacy Security Scan
runs-on: ubuntu-latest
steps:
# Checkout the repository to the GitHub Actions runner
- name: Checkout code
uses: actions/checkout@v2
# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
- name: Run Codacy Analysis CLI
uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b
with:
# Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository
# You can also omit the token and run the tools that support default configurations
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
verbose: true
output: results.sarif
format: sarif
# Adjust severity of non-security issues
gh-code-scanning-compat: true
# Force 0 exit code to allow SARIF file generation
# This will handover control about PR rejection to the GitHub side
max-allowed-issues: 2147483647
# Upload the SARIF file generated in the previous step
- name: Upload SARIF results file
uses: github/codeql-action/upload-sarif@v1
with:
sarif_file: results.sarif
+5 -5
View File
@@ -24,20 +24,20 @@ jobs:
distribution: 'adopt' distribution: 'adopt'
- name: Generate docs - name: Generate docs
run: mvn javadoc:javadoc run: mvn clean package -DskipTests
- name: Copy to Location - name: Copy to Location
run: | run: |
rm -rf docs rm -rf docs
mkdir -vp docs mkdir -vp docs
cp -vrf easysql-api/target/site/apidocs/* docs/ cp -vrf easysql-api/target/apidocs/* docs/
cp -vrf JAVADOC-README.md docs/README.md cp -vrf .documentation/JAVADOC-README.md docs/README.md
- name: Generate the sitemap - name: Generate the sitemap
id: sitemap id: sitemap
uses: cicirello/generate-sitemap@v1 uses: cicirello/generate-sitemap@v1
with: with:
base-url-path: https://carmjos.github.io/userprefix base-url-path: https://carmjos.github.io/EasySQL
path-to-root: docs path-to-root: docs
- name: Output stats - name: Output stats
@@ -62,7 +62,7 @@ jobs:
run: | run: |
cd docs cd docs
git init git init
git remote add origin git@github.com:CarmJos/UserPrefix.git git remote add origin git@github.com:CarmJos/EasySQL.git
git checkout -b gh-pages git checkout -b gh-pages
git add -A git add -A
git commit -m "API Document generated." git commit -m "API Document generated."
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
java-version: '11' java-version: '11'
distribution: 'adopt' distribution: 'adopt'
- name: "Package" - name: "Package"
run: mvn -B package --file pom.xml run: mvn -B package --file pom.xml -Dmaven.javadoc.skip=true
- name: "Target Stage" - name: "Target Stage"
run: mkdir staging && cp */target/*.jar staging run: mkdir staging && cp */target/*.jar staging
- name: "Upload artifact" - name: "Upload artifact"
+36
View File
@@ -0,0 +1,36 @@
name: Build
on:
push:
branches:
- master
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Cache SonarCloud packages
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v1
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: Build and analyze
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=CarmJos_EasySQL
+101 -80
View File
@@ -9,13 +9,13 @@
# EasySQL # EasySQL
[![CodeFactor](https://www.codefactor.io/repository/github/carmjos/easysql/badge)](https://www.codefactor.io/repository/github/carmjos/easysql) [![version](https://img.shields.io/github/v/release/CarmJos/EasySQL)](https://github.com/CarmJos/EasySQL/releases)
![CodeSize](https://img.shields.io/github/languages/code-size/CarmJos/EasySQL)
[![License](https://img.shields.io/github/license/CarmJos/EasySQL)](https://opensource.org/licenses/GPL-3.0) [![License](https://img.shields.io/github/license/CarmJos/EasySQL)](https://opensource.org/licenses/GPL-3.0)
[![workflow](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml/badge.svg?branch=master)](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml) [![workflow](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml/badge.svg?branch=master)](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml)
[![CodeFactor](https://www.codefactor.io/repository/github/carmjos/easysql/badge)](https://www.codefactor.io/repository/github/carmjos/easysql)
![CodeSize](https://img.shields.io/github/languages/code-size/CarmJos/EasySQL)
![](https://visitor-badge.glitch.me/badge?page_id=EasySQL.readme) ![](https://visitor-badge.glitch.me/badge?page_id=EasySQL.readme)
简单便捷的数据库操作工具,可自定义连接池来源。 简单便捷的数据库操作工具,可自定义连接池来源。
随项目分别提供 [BeeCP](https://github.com/Chris2018998/BeeCP) 与 [Hikari](https://github.com/brettwooldridge/HikariCP~~~~) 随项目分别提供 [BeeCP](https://github.com/Chris2018998/BeeCP) 与 [Hikari](https://github.com/brettwooldridge/HikariCP~~~~)
@@ -26,93 +26,54 @@
- 基于JDBC开发,可自选连接池、JDBC驱动。 - 基于JDBC开发,可自选连接池、JDBC驱动。
- 简单便捷的增删改查接口,无需手写SQL语句。 - 简单便捷的增删改查接口,无需手写SQL语句。
- 额外提供部分常用情况的SQL操作 - 额外提供部分常用情况的SQL操作
- 存在则更新,不存在则插入 - 自动关闭数据流
- 创建表
- 修改表
- ...
- 支持同步操作与异步操作 - 支持同步操作与异步操作
## 开发 ## 开发
详细开发介绍请 [点击这里](.documentation/INDEX.md) 。 详细开发介绍请 [点击这里](.documentation/README.md) , JavaDoc(最新Release) 请 [点击这里](https://carmjos.github.io/EasySQL) 。
### 示例代码 ### 示例代码
```java 您可以 [点击这里](easysql-demo/src/main/java/EasySQLDemo.java) 查看部分代码演示,更多演示详见 [开发介绍](.documentation/README.md) 。
public class EasySQLDemo {
public void createTable(SQLManager sqlManager) { ### 依赖方式
//异步创建表
sqlManager.createTable("users")
.addColumn("id", "INT(11) AUTO_INCREMENT NOT NULL PRIMARY KEY")
.addColumn("username", "VARCHAR(16) NOT NULL UNIQUE KEY")
.addColumn("email", "VARCHAR(32)")
.addColumn("phone", "VARCHAR(16)")
.addColumn("registerTime", "DATETIME NOT NULL")
.build().execute(null /* 不处理错误 */);
}
public void sqlQuery(SQLManager sqlManager) { #### Maven 依赖
// 同步SQL查询
try (SQLQuery query = sqlManager.createQuery()
.inTable("users") // 在users表中查询
.addCondition("id", ">", 5) // 限定 id 要大于5
.addCondition("email", null) // 限定查询email字段为空
.addNotNullCondition("phone") // 限定 phone字段不为空
.addTimeCondition(
"registerTime", // 时间字段
System.currentTimeMillis() - 100000, //限制开始时间
-1) //不限制结束时间
.build().execute()) {
ResultSet resultSet = query.getResultSet();
//do something
} catch (SQLException exception) { <details>
exception.printStackTrace(); <summary>远程库配置</summary>
}
}
public void sqlQueryAsync(SQLManager sqlManager) {
// 异步SQL查询
sqlManager.createQuery()
.inTable("users") // 在users表中查询
.addCondition("id", 5) // 限定 id 为 5
.setLimit(1).build().executeAsync(success -> {
ResultSet resultSet = success.getResultSet();
//do something
}, exception -> {
//do something
});
}
public void sqlInsert(SQLManager sqlManager) {
// 同步SQL插入 (不使用try-catch的情况下,返回的数值可能为空。)
Integer id = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setKeyIndex(1) // 设定自增主键的index,将会在后续返回自增主键
.execute(exception -> {
// 处理异常
});
}
}
```
更多演示详见开发介绍。
### 依赖方式 (Maven)
```xml ```xml
<project> <project>
<repositories> <repositories>
<repository> <repository>
<id>github</id> <!--采用github依赖库,安全稳定,但需要配置 (推荐)-->
<id>EasySQL</id>
<name>GitHub Packages</name> <name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/EasySQL</url> <url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
</repository> </repository>
<repository>
<!--采用我的私人依赖库,简单方便,但可能因为变故而无法使用-->
<id>carm-repo</id>
<name>Carm's Repo</name>
<url>https://repo.carm.cc/repository/maven-public/</url>
</repository>
</repositories> </repositories>
</project>
```
</details>
<details>
<summary>原生依赖</summary>
```xml
<project>
<dependencies> <dependencies>
<!--对于需要提供公共接口的项目,可以仅打包API部分,方便他人调用--> <!--对于需要提供公共接口的项目,可以仅打包API部分,方便他人调用-->
<dependency> <dependency>
@@ -130,14 +91,19 @@ public class EasySQLDemo {
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!--如需自定义连接池,则可以仅打包实现部分,自行创建SQLManager--> </dependencies>
<dependency> </project>
<groupId>cc.carm.lib</groupId> ```
<artifactId>easysql-beecp</artifactId>
<version>[LATEST RELEASE]</version>
<scope>compile</scope>
</dependency>
</details>
<details>
<summary>含连接池版本</summary>
```xml
<project>
<dependencies>
<!--也可直接选择打包了连接池的版本--> <!--也可直接选择打包了连接池的版本-->
<dependency> <dependency>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
@@ -151,12 +117,64 @@ public class EasySQLDemo {
<version>[LATEST VERSION]</version> <version>[LATEST VERSION]</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
``` ```
</details>
#### Gradle 依赖
<details>
<summary>远程库配置</summary>
```groovy
repositories {
// 采用github依赖库,安全稳定,但需要配置 (推荐)
maven { url 'https://maven.pkg.github.com/CarmJos/EasySQL' }
// 采用我的私人依赖库,简单方便,但可能因为变故而无法使用
maven { url 'https://repo.carm.cc/repository/maven-public/' }
}
```
</details>
<details>
<summary>原生依赖</summary>
```groovy
dependencies {
//对于需要提供公共接口的项目,可以仅打包API部分,方便他人调用
api "cc.carm.lib:easysql-api:[LATEST RELEASE]"
//如需自定义连接池,则可以仅打包实现部分,自行创建SQLManager
api "cc.carm.lib:easysql-impl:[LATEST RELEASE]"
}
```
</details>
<details>
<summary>含连接池版本</summary>
```groovy
dependencies {
//也可直接选择打包了连接池的版本
api "cc.carm.lib:easysql-beecp:[LATEST RELEASE]"
api "cc.carm.lib:easysql-hikaricp:[LATEST RELEASE]"
}
```
</details>
## 支持与捐赠 ## 支持与捐赠
若您觉得本插件做的不错,您可以通过捐赠支持我! 若您觉得本插件做的不错,您可以通过捐赠支持我!
@@ -168,7 +186,9 @@ public class EasySQLDemo {
## 开源协议 ## 开源协议
本项目源码采用 [GNU General Public License v3.0](https://opensource.org/licenses/GPL-3.0) 开源协议。 本项目源码采用 [GNU General Public License v3.0](https://opensource.org/licenses/GPL-3.0) 开源协议。
> ### 关于 GPL 协议 <details>
<summary>关于 GPL 协议</summary>
> GNU General Public Licence (GPL) 有可能是开源界最常用的许可模式。GPL 保证了所有开发者的权利,同时为使用者提供了足够的复制,分发,修改的权利: > GNU General Public Licence (GPL) 有可能是开源界最常用的许可模式。GPL 保证了所有开发者的权利,同时为使用者提供了足够的复制,分发,修改的权利:
> >
> #### 可自由复制 > #### 可自由复制
@@ -183,3 +203,4 @@ public class EasySQLDemo {
> 需要注意的是,分发的时候,需要明确提供源代码和二进制文件,另外,用于某些程序的某些协议有一些问题和限制,你可以看一下 @PierreJoye 写的 Practical Guide to GPL Compliance 一文。使用 GPL 协议,你必须在源代码代码中包含相应信息,以及协议本身。 > 需要注意的是,分发的时候,需要明确提供源代码和二进制文件,另外,用于某些程序的某些协议有一些问题和限制,你可以看一下 @PierreJoye 写的 Practical Guide to GPL Compliance 一文。使用 GPL 协议,你必须在源代码代码中包含相应信息,以及协议本身。
> >
> *以上文字来自 [五种开源协议GPL,LGPL,BSD,MIT,Apache](https://www.oschina.net/question/54100_9455) 。* > *以上文字来自 [五种开源协议GPL,LGPL,BSD,MIT,Apache](https://www.oschina.net/question/54100_9455) 。*
</details>
+3 -3
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<version>v0.0.1</version> <version>0.2.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -46,8 +46,8 @@
</ciManagement> </ciManagement>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
@@ -1,58 +1,164 @@
package cc.carm.lib.easysql.api; package cc.carm.lib.easysql.api;
import cc.carm.lib.easysql.api.function.SQLFunction;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.UUID; import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
/**
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
*
* <ul>
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, BiConsumer)}
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
*
* <li>异步执行 {@link #executeAsync(Consumer, BiConsumer)}
* <br>异步执行时将提供成功与异常两种处理方式
* <br>可自行选择是否对数据或异常进行处理
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}</li>
* </ul>
*
* @param <T> 需要返回的类型
* @author CarmJos
* @since 0.0.1
*/
public interface SQLAction<T> { public interface SQLAction<T> {
/**
* 得到该Action的UUID
*
* @return UUID
*/
@NotNull UUID getActionUUID(); @NotNull UUID getActionUUID();
/**
* 得到短八位格式的UUID
*
* @return UUID(8)
*/
@NotNull String getShortID(); @NotNull String getShortID();
/**
* 得到该Action的创建时间
*
* @return 创建时间
*/
long getCreateTime(); long getCreateTime();
/**
* 得到该Action所要执行的源SQL语句
*
* @return 源SQL语句
*/
@NotNull String getSQLContent(); @NotNull String getSQLContent();
/**
* 得到承载该Action的对应{@link SQLManager}
*
* @return {@link SQLManager}
*/
@NotNull SQLManager getManager(); @NotNull SQLManager getManager();
/**
* 执行该Action对应的SQL语句
*
* @return 指定数据类型
* @throws SQLException 当SQL操作出现问题时抛出
*/
@NotNull T execute() throws SQLException; @NotNull T execute() throws SQLException;
/**
* 执行语句并返回值
*
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
* @return 指定类型数据
*/
@Nullable @Nullable
default T execute(@Nullable Consumer<SQLException> exceptionHandler) { default T execute(@Nullable BiConsumer<SQLException, SQLAction<T>> exceptionHandler) {
if (exceptionHandler == null) exceptionHandler = defaultExceptionHandler(); return execute(t -> t, exceptionHandler);
T value = null;
try {
value = execute();
} catch (SQLException exception) {
exceptionHandler.accept(exception);
}
return value;
} }
/**
* 执行语句并处理返回值
*
* @param function 处理方法
* @param <R> 需要返回的内容
* @return 指定类型数据
* @throws SQLException 当SQL操作出现问题时抛出
*/
@Nullable
default <R> R executeFunction(@NotNull SQLFunction<T, R> function) throws SQLException {
try {
T value = execute();
return function.apply(value);
} catch (SQLException exception) {
throw new SQLException(exception);
}
}
/**
* 执行语句并处理返回值
*
* @param function 处理方法
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
* @param <R> 需要返回的内容
* @return 指定类型数据
*/
@Nullable
default <R> R execute(@NotNull SQLFunction<T, R> function,
@Nullable BiConsumer<SQLException, SQLAction<T>> exceptionHandler) {
try {
return executeFunction(function);
} catch (SQLException exception) {
handleException(exceptionHandler, exception);
return null;
}
}
/**
* 异步执行SQL语句,采用默认异常处理,无需返回值。
*/
default void executeAsync() { default void executeAsync() {
executeAsync(null); executeAsync(null);
} }
default void executeAsync(Consumer<T> success) { /**
* 异步执行SQL语句
*
* @param success 成功时的操作
*/
default void executeAsync(@Nullable Consumer<T> success) {
executeAsync(success, null); executeAsync(success, null);
} }
void executeAsync(Consumer<T> success, Consumer<SQLException> failure); /**
* 异步执行SQL语句
*
* @param success 成功时的操作
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
*/
void executeAsync(@Nullable Consumer<T> success, @Nullable BiConsumer<SQLException, SQLAction<T>> failure);
SQLAction<T> handleException(Consumer<SQLException> failure);
@NotNull Consumer<SQLException> getExceptionHandler(); default void handleException(@Nullable BiConsumer<SQLException, SQLAction<T>> handler, SQLException exception) {
if (handler == null) handler = defaultExceptionHandler();
default Consumer<SQLException> defaultExceptionHandler() { handler.accept(exception, this);
return Throwable::printStackTrace;
} }
default Consumer<T> defaultResultHandler() { /**
return t -> { * @return 默认的异常处理器
*/
default BiConsumer<SQLException, SQLAction<T>> defaultExceptionHandler() {
return (exception, action) -> {
getManager().getLogger().severe("Error when execute [" + action.getSQLContent() + "]");
getManager().getLogger().severe(exception.getLocalizedMessage());
exception.printStackTrace();
}; };
} }
@@ -2,8 +2,20 @@ package cc.carm.lib.easysql.api;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/**
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
* <br>也是本接口的核心功能所在
*
* @author CarmJos
*/
public interface SQLBuilder { public interface SQLBuilder {
/**
* 得到承载该Builder的对应{@link SQLManager}
*
* @return {@link SQLManager}
*/
@NotNull SQLManager getManager(); @NotNull SQLManager getManager();
} }
@@ -2,6 +2,9 @@ package cc.carm.lib.easysql.api;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.builder.*; import cc.carm.lib.easysql.api.builder.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -12,9 +15,12 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger;
public interface SQLManager { public interface SQLManager {
Logger getLogger();
boolean isDebugMode(); boolean isDebugMode();
void setDebugMode(boolean enable); void setDebugMode(boolean enable);
@@ -30,6 +36,7 @@ public interface SQLManager {
* 得到一个数据库连接实例 * 得到一个数据库连接实例
* *
* @return Connection * @return Connection
* @throws SQLException 见 {@link DataSource#getConnection()}
*/ */
@NotNull Connection getConnection() throws SQLException; @NotNull Connection getConnection() throws SQLException;
@@ -42,53 +49,115 @@ public interface SQLManager {
/** /**
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法) * 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
* 该方法使用 Statement 实现,请注意SQL注入风险!
* *
* @param sql SQL语句内容 * @param sql SQL语句内容
* @return 更新的行数 * @return 更新的行数
* @see SQLUpdateAction
*/ */
@Nullable Integer executeSQL(String sql); @Nullable Integer executeSQL(String sql);
/** /**
* 执行一条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE) * 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
* *
* @param sql SQL语句内容 * @param sql SQL语句内容
* @param params SQL语句中 ? 的对应参数
* @return 更新的行数 * @return 更新的行数
* @see PreparedSQLUpdateAction
*/ */
@Nullable Integer executeSQL(String sql, Object[] params); @Nullable Integer executeSQL(String sql, Object[] params);
/** /**
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE) * 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
* *
* @param sql SQL语句内容 * @param sql SQL语句内容
* @param paramsBatch SQL语句中对应?的参数组
* @return 对应参数返回的行数 * @return 对应参数返回的行数
* @see PreparedSQLUpdateBatchAction
*/ */
@Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch); @Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
/** /**
* 执行多条不需要返回结果的SQL。 * 执行多条不需要返回结果的SQL。
* 该方法使用 Statement 实现,请注意SQL注入风险!
* *
* @param sql SQL语句内容 * @param sql SQL语句内容
* @param moreSQL 更多SQL语句内容
* @return 对应参数返回的行数 * @return 对应参数返回的行数
* @see SQLUpdateBatchAction
*/ */
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL); @Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
/**
* 执行多条不需要返回结果的SQL。
*
* @param sqlBatch SQL语句内容
* @return 对应参数返回的行数
*/
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch); @Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
/**
* 在库中创建一个表
*
* @param tableName 表名
* @return {@link TableCreateBuilder}
*/
TableCreateBuilder createTable(@NotNull String tableName); TableCreateBuilder createTable(@NotNull String tableName);
/**
* 新建一个查询
*
* @return {@link QueryBuilder}
*/
QueryBuilder createQuery(); QueryBuilder createQuery();
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName); /**
* 创建一条插入操作
*
* @param tableName 目标表名
* @return {@link InsertBuilder}
*/
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName); InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName);
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName); /**
* 创建支持多组数据的插入操作
*
* @param tableName 目标表名
* @return {@link InsertBuilder}
*/
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
/**
* 创建一条替换操作
*
* @param tableName 目标表名
* @return {@link ReplaceBuilder}
*/
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName); ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName);
/**
* 创建支持多组数据的替换操作
*
* @param tableName 目标表名
* @return {@link ReplaceBuilder}
*/
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
/**
* 创建更新操作
*
* @param tableName 目标表名
* @return {@link UpdateBuilder}
*/
UpdateBuilder createUpdate(@NotNull String tableName); UpdateBuilder createUpdate(@NotNull String tableName);
/**
* 创建删除操作
*
* @param tableName 目标表名
* @return {@link DeleteBuilder}
*/
DeleteBuilder createDelete(@NotNull String tableName); DeleteBuilder createDelete(@NotNull String tableName);
} }
@@ -1,7 +1,23 @@
package cc.carm.lib.easysql.api.action; package cc.carm.lib.easysql.api.action;
import org.jetbrains.annotations.Nullable;
public interface PreparedSQLUpdateAction extends SQLUpdateAction { public interface PreparedSQLUpdateAction extends SQLUpdateAction {
/**
* 设定SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedSQLUpdateAction}
*/
PreparedSQLUpdateAction setParams(Object... params); PreparedSQLUpdateAction setParams(Object... params);
/**
* 设定SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedSQLUpdateAction}
*/
PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params);
} }
@@ -6,12 +6,37 @@ import java.util.List;
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> { public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
/**
* 设定多组SQL语句中所有 ? 对应的参数
*
* @param allParams 所有参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams); PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
/**
* 添加一组SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction addParamsBatch(Object... params); PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex); PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex);
/**
* 默认主键序列的数值为 -1 (≤0) ,即默认返回发生变更的行数。
*
* @return 默认主键序列
*/
default PreparedSQLUpdateBatchAction defaultKeyIndex() { default PreparedSQLUpdateBatchAction defaultKeyIndex() {
return setKeyIndex(-1); // will return changed lines number return setKeyIndex(-1); // will return changed lines number
} }
@@ -2,12 +2,31 @@ package cc.carm.lib.easysql.api.action;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
import java.sql.SQLException;
import java.util.List;
import java.util.function.BiConsumer;
public interface SQLUpdateAction extends SQLAction<Integer> { public interface SQLUpdateAction extends SQLAction<Integer> {
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link SQLUpdateAction}
*/
SQLUpdateAction setKeyIndex(int keyColumnIndex); SQLUpdateAction setKeyIndex(int keyColumnIndex);
/**
* 默认主键序列的数值为 -1 (≤0) ,即默认返回发生变更的行数。
*
* @return 默认主键序列
*/
default SQLUpdateAction defaultKeyIndex() { default SQLUpdateAction defaultKeyIndex() {
return setKeyIndex(-1); // will return changed lines number return setKeyIndex(-1); // will return changed lines number
} }
} }
@@ -3,10 +3,34 @@ package cc.carm.lib.easysql.api.action;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.function.BiConsumer;
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> { public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
/**
* 添加一条批量执行的SQL语句
*
* @param sql SQL语句
* @return {@link SQLUpdateBatchAction}
*/
SQLUpdateBatchAction addBatch(@NotNull String sql); SQLUpdateBatchAction addBatch(@NotNull String sql);
List<String> getSQLContents();
@Override
default BiConsumer<SQLException, SQLAction<List<Integer>>> defaultExceptionHandler() {
return (exception, action) -> {
getManager().getLogger().severe("Error when execute SQLs : ");
int i = 1;
for (String content : getSQLContents()) {
getManager().getLogger().severe("#" + i + " [" + content + "]");
i++;
}
getManager().getLogger().severe(exception.getLocalizedMessage());
exception.printStackTrace();
};
}
} }
@@ -7,10 +7,29 @@ import java.util.function.Consumer;
public interface PreparedQueryAction extends QueryAction { public interface PreparedQueryAction extends QueryAction {
/**
* 设定SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedQueryAction}
*/
PreparedQueryAction setParams(@Nullable Object... params); PreparedQueryAction setParams(@Nullable Object... params);
/**
* 设定SQL语句中所有 ? 对应的参数
*
* @param params 参数内容
* @return {@link PreparedQueryAction}
*/
PreparedQueryAction setParams(@Nullable Iterable<Object> params); PreparedQueryAction setParams(@Nullable Iterable<Object> params);
/**
* 直接对 {@link PreparedStatement} 进行处理
*
* @param statement {@link Consumer} 处理操作
* 若为空则不进行处理
* @return {@link PreparedQueryAction}
*/
PreparedQueryAction handleStatement(@Nullable Consumer<PreparedStatement> statement); PreparedQueryAction handleStatement(@Nullable Consumer<PreparedStatement> statement);
} }
@@ -1,8 +1,51 @@
package cc.carm.lib.easysql.api.action.query; package cc.carm.lib.easysql.api.action.query;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.api.SQLQuery; import cc.carm.lib.easysql.api.function.SQLFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* SQLQueryAction 是用于承载SQL查询语句并进行处理、返回并自动关闭连接的基本类。
*
* <ul>
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, BiConsumer)}
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
*
* <li>异步执行 {@link #executeAsync(Consumer, BiConsumer)}
* <br>异步执行时将提供成功与异常两种处理方式
* <br>可自行选择是否对数据或异常进行处理
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}</li>
* </ul>
*
* <b>注意: 无论是否异步,都不需要自行关闭ResultSet,本API已自动关闭</b>
*
* @author CarmJos
* @since 0.2.6
*/
public interface QueryAction extends SQLAction<SQLQuery> { public interface QueryAction extends SQLAction<SQLQuery> {
/**
* 执行语句并处理返回值
*
* @param function 处理方法
* @param <R> 需要返回的内容
* @return 指定类型数据
* @throws SQLException 当SQL操作出现问题时抛出
*/
@Nullable
default <R> R executeFunction(@NotNull SQLFunction<SQLQuery, R> function)
throws SQLException {
try (SQLQuery value = execute()) {
return function.apply(value);
} catch (SQLException exception) {
throw new SQLException(exception);
}
}
} }
@@ -1,6 +1,6 @@
package cc.carm.lib.easysql.api; package cc.carm.lib.easysql.api.action.query;
import cc.carm.lib.easysql.api.action.query.QueryAction; import cc.carm.lib.easysql.api.SQLManager;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -15,8 +15,18 @@ public interface SQLQuery extends AutoCloseable {
*/ */
long getExecuteTime(); long getExecuteTime();
/**
* 得到承载该SQLQuery的对应{@link SQLManager}
*
* @return {@link SQLManager}
*/
SQLManager getManager(); SQLManager getManager();
/**
* 得到承载该SQLQuery的对应{@link QueryAction}
*
* @return {@link QueryAction} {@link PreparedQueryAction}
*/
QueryAction getAction(); QueryAction getAction();
ResultSet getResultSet(); ResultSet getResultSet();
@@ -7,36 +7,36 @@ import org.jetbrains.annotations.Nullable;
import java.util.Date; import java.util.Date;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
public interface ConditionalBuilder<T> extends SQLBuilder { public interface ConditionalBuilder<B extends ConditionalBuilder<B, T>, T> extends SQLBuilder {
T build(); T build();
ConditionalBuilder<T> setLimit(int limit); B setLimit(int limit);
ConditionalBuilder<T> setConditions(@Nullable String condition); B setConditions(@Nullable String condition);
ConditionalBuilder<T> setConditions(LinkedHashMap<@NotNull String, @Nullable Object> conditionSQLs); B setConditions(LinkedHashMap<@NotNull String, @Nullable Object> conditionSQLs);
ConditionalBuilder<T> addCondition(@Nullable String condition); B addCondition(@Nullable String condition);
ConditionalBuilder<T> addCondition(@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue); B addCondition(@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue);
default ConditionalBuilder<T> addCondition(@NotNull String queryName, @Nullable Object queryValue) { default B addCondition(@NotNull String queryName, @Nullable Object queryValue) {
return addCondition(queryName, "=", queryValue); return addCondition(queryName, "=", queryValue);
} }
ConditionalBuilder<T> addCondition(@NotNull String[] queryNames, @Nullable Object[] queryValues); B addCondition(@NotNull String[] queryNames, @Nullable Object[] queryValues);
ConditionalBuilder<T> addNotNullCondition(@NotNull String queryName); B addNotNullCondition(@NotNull String queryName);
default ConditionalBuilder<T> addTimeCondition(@NotNull String queryName, long startMillis, long endMillis) { default B addTimeCondition(@NotNull String queryName, long startMillis, long endMillis) {
return addTimeCondition(queryName, return addTimeCondition(queryName,
startMillis > 0 ? new Date(startMillis) : null, startMillis > 0 ? new Date(startMillis) : null,
endMillis > 0 ? new Date(endMillis) : null endMillis > 0 ? new Date(endMillis) : null
); );
} }
ConditionalBuilder<T> addTimeCondition(@NotNull String queryName, @Nullable java.util.Date startDate, @Nullable java.util.Date endDate); B addTimeCondition(@NotNull String queryName, @Nullable java.util.Date startDate, @Nullable java.util.Date endDate);
} }
@@ -2,7 +2,7 @@ package cc.carm.lib.easysql.api.builder;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
public interface DeleteBuilder extends ConditionalBuilder<PreparedSQLUpdateAction> { public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, PreparedSQLUpdateAction> {
String getTableName(); String getTableName();
@@ -7,8 +7,6 @@ public interface InsertBuilder<T> {
String getTableName(); String getTableName();
InsertBuilder<T> setTableName(String tableName);
T setColumnNames(List<String> columnNames); T setColumnNames(List<String> columnNames);
default T setColumnNames(String... columnNames) { default T setColumnNames(String... columnNames) {
@@ -7,10 +7,31 @@ import org.jetbrains.annotations.NotNull;
public interface QueryBuilder extends SQLBuilder { public interface QueryBuilder extends SQLBuilder {
/**
* 通过一条 SQL语句创建查询。
* 该方法使用 Statement 实现,请注意SQL注入风险!
*
* @param sql SQL语句
* @return {@link QueryAction}
* @deprecated 存在SQL注入风险,建议使用 {@link QueryBuilder#withPreparedSQL(String)}
*/
@Deprecated
QueryAction withSQL(@NotNull String sql); QueryAction withSQL(@NotNull String sql);
/**
* 通过一条 SQL语句创建预查询
*
* @param sql SQL语句
* @return {@link PreparedQueryAction}
*/
PreparedQueryAction withPreparedSQL(@NotNull String sql); PreparedQueryAction withPreparedSQL(@NotNull String sql);
/**
* 创建表查询
*
* @param tableName 表名
* @return {@link TableQueryBuilder}
*/
TableQueryBuilder inTable(@NotNull String tableName); TableQueryBuilder inTable(@NotNull String tableName);
} }
@@ -7,8 +7,6 @@ public interface ReplaceBuilder<T> {
String getTableName(); String getTableName();
ReplaceBuilder<T> setTableName(String tableName);
T setColumnNames(List<String> columnNames); T setColumnNames(List<String> columnNames);
default T setColumnNames(String... columnNames) { default T setColumnNames(String... columnNames) {
@@ -8,8 +8,6 @@ public interface TableCreateBuilder extends SQLBuilder {
@NotNull String getTableName(); @NotNull String getTableName();
TableCreateBuilder setTableName(@NotNull String tableName);
@NotNull String getTableSettings(); @NotNull String getTableSettings();
TableCreateBuilder setTableSettings(@NotNull String settings); TableCreateBuilder setTableSettings(@NotNull String settings);
@@ -3,10 +3,35 @@ package cc.carm.lib.easysql.api.builder;
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction; import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public interface TableQueryBuilder extends ConditionalBuilder<PreparedQueryAction> { public interface TableQueryBuilder extends ConditionalBuilder<TableQueryBuilder, PreparedQueryAction> {
@NotNull String getTableName(); @NotNull String getTableName();
/**
* 选定用于查询的列名
*
* @param columnNames 列名
* @return {@link TableQueryBuilder}
*/
TableQueryBuilder selectColumns(@NotNull String... columnNames); TableQueryBuilder selectColumns(@NotNull String... columnNames);
/**
* 对结果进行排序
*
* @param columnName 排序使用的列名
* @param asc 是否为正序排序 (为false则倒序排序)
* @return {@link TableQueryBuilder}
*/
TableQueryBuilder orderBy(@NotNull String columnName, boolean asc);
/**
* 限制查询条数,用于分页查询。
*
* @param start 开始数
* @param end 结束条数
* @return {@link TableQueryBuilder}
* @since 0.2.6
*/
TableQueryBuilder setPageLimit(int start, int end);
} }
@@ -4,7 +4,7 @@ import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
public interface UpdateBuilder extends ConditionalBuilder<PreparedSQLUpdateAction> { public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, PreparedSQLUpdateAction> {
String getTableName(); String getTableName();
@@ -0,0 +1,9 @@
package cc.carm.lib.easysql.api.builder;
public interface UpsertBuilder {
String getTableName();
UpsertBuilder setColumnNames(String[] columnNames, String updateColumn);
}
@@ -1,9 +0,0 @@
package cc.carm.lib.easysql.api.enums;
public enum ReturnedType {
AUTO_INCREASE_KEY,
CHANGED_LINES
}
@@ -0,0 +1,12 @@
package cc.carm.lib.easysql.api.function;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
public interface SQLFunction<T, R> {
@Nullable
R apply(T t) throws SQLException;
}
@@ -11,19 +11,42 @@ public class TimeDateUtils {
public TimeDateUtils() { public TimeDateUtils() {
} }
/**
* 得到当前时间文本。
*
* @return 时间文本 格式{@link TimeDateUtils#getFormat()}
*/
public static String getCurrentTime() { public static String getCurrentTime() {
return getFormat().format(new Date()); return getTimeString(System.currentTimeMillis());
} }
/**
* 得到一个时间戳的文本
*
* @param timeMillis 时间戳
* @return 时间文本 格式{@link TimeDateUtils#getFormat()}
*/
public static String getTimeString(long timeMillis) { public static String getTimeString(long timeMillis) {
return getFormat().format(new Date(timeMillis)); return getFormat().format(new Date(timeMillis));
} }
/**
* 得到一个日期时间的文本
*
* @param time 日期时间
* @return 时间文本 格式{@link TimeDateUtils#getFormat()}
*/
public static String getTimeString(Date time) { public static String getTimeString(Date time) {
return getFormat().format(time); return getFormat().format(time);
} }
public static long getTimeMillis(String timeString) { /**
* 得到一个时间文本的时间戳
*
* @param timeString 时间文本
* @return 时间戳 格式{@link TimeDateUtils#getFormat()}
*/
public static long parseTimeMillis(String timeString) {
if (timeString == null) { if (timeString == null) {
return -1L; return -1L;
} else { } else {
@@ -35,6 +58,13 @@ public class TimeDateUtils {
} }
} }
/**
* 得到一个时间文本的对应日期实例
*
* @param timeString 时间文本
* @return 日期实例 格式{@link TimeDateUtils#getFormat()}
*/
public static Date getTimeDate(String timeString) { public static Date getTimeDate(String timeString) {
if (timeString == null) { if (timeString == null) {
return null; return null;
@@ -47,6 +77,12 @@ public class TimeDateUtils {
} }
} }
/**
* 将秒数转化为 DD:hh:mm:ss 格式
*
* @param allSeconds 秒数
* @return DD:hh:mm:ss格式文本
*/
public static String toDHMSStyle(long allSeconds) { public static String toDHMSStyle(long allSeconds) {
long days = allSeconds / 86400L; long days = allSeconds / 86400L;
long hours = allSeconds % 86400L / 3600L; long hours = allSeconds % 86400L / 3600L;
+32 -4
View File
@@ -5,14 +5,14 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>v0.0.1</version> <version>0.2.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>easysql-beecp</artifactId> <artifactId>easysql-beecp</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>10-EasySQL-BeeCP</name> <name>12-EasySQL-BeeCP</name>
<description>EasySQL的应用部分。此为BeeCP版本。</description> <description>EasySQL的应用部分。此为BeeCP版本。</description>
<url>https://github.com/CarmJos/EasySQL</url> <url>https://github.com/CarmJos/EasySQL</url>
@@ -46,10 +46,11 @@
</ciManagement> </ciManagement>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties> </properties>
<dependencies> <dependencies>
@@ -66,6 +67,7 @@
<groupId>com.github.chris2018998</groupId> <groupId>com.github.chris2018998</groupId>
<artifactId>beecp</artifactId> <artifactId>beecp</artifactId>
<version>3.3.0</version> <version>3.3.0</version>
<optional>true</optional>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -88,6 +90,32 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>cn.beecp</pattern>
<shadedPattern>cc.carm.lib.easysql.beecp</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
<exclude>META-INF/*.txt</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
@@ -1,5 +1,8 @@
package cc.carm.lib.easysql; package cc.carm.lib.easysql;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.util.TimeDateUtils;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import cn.beecp.BeeDataSource; import cn.beecp.BeeDataSource;
import cn.beecp.BeeDataSourceConfig; import cn.beecp.BeeDataSourceConfig;
@@ -18,4 +21,26 @@ public class EasySQL {
return new SQLManagerImpl(new BeeDataSource(config)); return new SQLManagerImpl(new BeeDataSource(config));
} }
public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) {
if (!manager.getActiveQuery().isEmpty()) {
manager.getLogger().severe("There are " + manager.getActiveQuery().size() + " connections still running");
for (SQLQuery value : manager.getActiveQuery().values()) {
if (outputActiveQuery) {
manager.getLogger().severe("#" + value.getAction().getShortID() + " -> " + value.getSQLContent());
manager.getLogger().severe("- execute at " + TimeDateUtils.getTimeString(value.getExecuteTime()));
}
if (forceClose) value.close();
}
}
if (manager.getDataSource() instanceof BeeDataSource) {
//Close bee connection pool
((BeeDataSource) manager.getDataSource()).close();
}
}
public static void shutdownManager(SQLManager manager) {
shutdownManager(manager, true, manager.isDebugMode());
}
} }
+80
View File
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>easysql-demo</artifactId>
<packaging>jar</packaging>
<name>99-EasySQL-Demo</name>
<description>EasySQL的演示部分</description>
<url>https://github.com/CarmJos/EasySQL</url>
<developers>
<developer>
<id>CarmJos</id>
<name>Carm Jos</name>
<email>carm@carm.cc</email>
<url>https://www.carm.cc</url>
<roles>
<role>Main Developer</role>
</roles>
</developer>
</developers>
<licenses>
<license>
<name>GNU General Public License v3.0</name>
<url>https://opensource.org/licenses/GPL-3.0</url>
</license>
</licenses>
<issueManagement>
<system>GitHub Issues</system>
<url>${project.url}/issues</url>
</issueManagement>
<ciManagement>
<system>GitHub Actions</system>
<url>${project.url}/actions/workflows/maven.yml</url>
</ciManagement>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.javadoc.skip>true</maven.javadoc.skip>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>${project.parent.groupId}</groupId>
<artifactId>easysql-impl</artifactId>
<version>${project.parent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+108
View File
@@ -0,0 +1,108 @@
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.util.TimeDateUtils;
import cc.carm.lib.easysql.api.util.UUIDUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
public class EasySQLDemo {
public void createTable(SQLManager sqlManager) {
// 同步创建表
sqlManager.createTable("users")
.addColumn("id", "INT(11) AUTO_INCREMENT NOT NULL PRIMARY KEY")
.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY")
.addColumn("username", "VARCHAR(16) NOT NULL UNIQUE KEY")
.addColumn("age", "INT(3) NOT NULL DEFAULT 1")
.addColumn("email", "VARCHAR(32)")
.addColumn("phone", "VARCHAR(16)")
.addColumn("registerTime", "DATETIME NOT NULL")
.build().execute(null /* 不处理错误 */);
}
public void sqlQuery(SQLManager sqlManager) {
// 同步SQL查询
try (SQLQuery query = sqlManager.createQuery()
.inTable("users") // 在users表中查询
.selectColumns("id", "name") // 选中 id 与 name列
.addCondition("age", ">", 18) // 限定 age 要大于5
.addCondition("email", null) // 限定查询 email 字段为空
.addNotNullCondition("phone") // 限定 phone 字段不为空
.addTimeCondition("registerTime", // 时间字段
System.currentTimeMillis() - 100000, //限制开始时间
-1//不限制结束时间
).build().execute()) {
ResultSet resultSet = query.getResultSet();
//do something
} catch (SQLException exception) {
exception.printStackTrace();
}
UUID userUUID = sqlManager.createQuery()
.inTable("users") // 在users表中查询
.selectColumns("uuid")
.addCondition("id", 5) // 限定 id 为 5
.setLimit(1) // 只取出一个数据
.build().execute(query -> {
//可以直接进行数据处理
ResultSet result = query.getResultSet();
return result.next() ? UUIDUtil.toUUID(result.getString("uuid")) : null;
}, (exception, action) -> {
// 处理异常,不想处理直接填null
});
}
public void sqlQueryAsync(SQLManager sqlManager) {
// 异步SQL查询
sqlManager.createQuery()
.inTable("users") // 在users表中查询
.addCondition("id", 5) // 限定 id 为 5
.setLimit(1) // 只取出一个数据
.build().executeAsync(success -> {
ResultSet resultSet = success.getResultSet();
try {
if (resultSet != null && resultSet.next()) {
String username = resultSet.getString("username");
}
} catch (SQLException e) {
e.printStackTrace();
}
}, (exception, action) -> {
//do something
long createTIme = action.getCreateTime();
String shortID = action.getShortID();
String sqlContent = action.getSQLContent();
});
}
public void sqlInsert(SQLManager sqlManager) {
// 同步SQL插入 (不使用try-catch的情况下,返回的数值可能为空。)
Integer id = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setKeyIndex(1) // 设定自增主键的index,将会在后续返回自增主键
.execute((exception, action) -> {
// 处理异常
System.out.println("#" + action.getShortID() + " -> " + action.getSQLContent());
exception.printStackTrace();
});
try {
Integer userID = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setKeyIndex(1) // 设定自增主键的index,将会在后续返回自增主键
.execute();
System.out.println("新用户的ID为 " + userID);
} catch (SQLException exception) {
exception.printStackTrace();
}
}
}
+31 -3
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>v0.0.1</version> <version>0.2.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -45,10 +45,11 @@
</ciManagement> </ciManagement>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties> </properties>
<dependencies> <dependencies>
@@ -65,6 +66,7 @@
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>4.0.3</version> <version>4.0.3</version>
<optional>true</optional>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -87,6 +89,32 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>com.zaxxer.hikari</pattern>
<shadedPattern>cc.carm.lib.easysql.hikari</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
<exclude>META-INF/*.txt</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
@@ -0,0 +1,56 @@
package cc.carm.lib.easysql;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.util.TimeDateUtils;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Properties;
public class EasySQL {
public static SQLManagerImpl createManager(
@NotNull String driver, @NotNull String url,
@NotNull String username, @Nullable String password) {
HikariConfig config = new HikariConfig();
config.setDriverClassName(driver);
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
return createManager(config);
}
public static SQLManagerImpl createManager(@NotNull Properties properties) {
return createManager(new HikariConfig(properties));
}
public static SQLManagerImpl createManager(@NotNull HikariConfig config) {
return new SQLManagerImpl(new HikariDataSource(config));
}
public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) {
if (!manager.getActiveQuery().isEmpty()) {
manager.getLogger().severe("There are " + manager.getActiveQuery().size() + " connections still running");
for (SQLQuery value : manager.getActiveQuery().values()) {
if (outputActiveQuery) {
manager.getLogger().severe("#" + value.getAction().getShortID() + " -> " + value.getSQLContent());
manager.getLogger().severe("- execute at " + TimeDateUtils.getTimeString(value.getExecuteTime()));
}
if (forceClose) value.close();
}
}
if (manager.getDataSource() instanceof HikariDataSource) {
//Close hikari pool
((HikariDataSource) manager.getDataSource()).close();
}
}
public static void shutdownManager(SQLManager manager) {
shutdownManager(manager, true, manager.isDebugMode());
}
}
@@ -1,32 +0,0 @@
package easysql;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Properties;
public class EasySQL {
public static SQLManagerImpl createManager(
@NotNull String driver, @NotNull String url,
@NotNull String username, @Nullable String password) {
HikariConfig config = new HikariConfig();
config.setDriverClassName(driver);
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
return createManager(config);
}
public static SQLManagerImpl createManager(@NotNull Properties properties) {
return createManager(new HikariConfig(properties));
}
public static SQLManagerImpl createManager(@NotNull HikariConfig config) {
return new SQLManagerImpl(new HikariDataSource(config));
}
}
+4 -3
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>v0.0.1</version> <version>0.2.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@@ -46,10 +46,11 @@
</ciManagement> </ciManagement>
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties> </properties>
<dependencies> <dependencies>
@@ -3,9 +3,11 @@ package cc.carm.lib.easysql.action;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.UUID; import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
public abstract class AbstractSQLAction<T> implements SQLAction<T> { public abstract class AbstractSQLAction<T> implements SQLAction<T> {
@@ -17,7 +19,7 @@ public abstract class AbstractSQLAction<T> implements SQLAction<T> {
protected @NotNull String sqlContent; protected @NotNull String sqlContent;
protected @NotNull Consumer<SQLException> exceptionHandler = defaultExceptionHandler(); protected @Nullable BiConsumer<SQLException, SQLAction<T>> exceptionHandler = null;
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) { public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
this(manager, sql, System.currentTimeMillis()); this(manager, sql, System.currentTimeMillis());
@@ -69,14 +71,25 @@ public abstract class AbstractSQLAction<T> implements SQLAction<T> {
getManager().debug("#" + getShortID() + " ->" + getSQLContent()); getManager().debug("#" + getShortID() + " ->" + getSQLContent());
} }
@Override public void handleException(SQLException exception) {
public SQLAction<T> handleException(Consumer<SQLException> handler) { if (this.exceptionHandler == null) {
this.exceptionHandler = handler; defaultExceptionHandler().accept(exception, this);
return this; } else {
this.exceptionHandler.accept(exception, this);
}
} }
@NotNull @Override
public Consumer<SQLException> getExceptionHandler() { public void executeAsync(Consumer<T> success, BiConsumer<SQLException, SQLAction<T>> failure) {
return exceptionHandler; getManager().getExecutorPool().submit(() -> {
try {
T returnedValue = execute();
if (success != null) success.accept(returnedValue);
} catch (SQLException e) {
(failure == null ? defaultExceptionHandler() : failure).accept(e, this);
}
});
} }
} }
@@ -12,10 +12,9 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class PreparedSQLBatchUpdateActionImpl extends SQLUpdateBatchActionImpl implements PreparedSQLUpdateBatchAction { public class PreparedSQLBatchUpdateActionImpl extends AbstractSQLAction<List<Integer>> implements PreparedSQLUpdateBatchAction {
int keyIndex = -1; int keyIndex = -1;
List<Object[]> allParams; List<Object[]> allParams;
@@ -54,6 +53,7 @@ public class PreparedSQLBatchUpdateActionImpl extends SQLUpdateBatchActionImpl i
); );
outputDebugMessage(); outputDebugMessage();
if (keyIndex > 0) { if (keyIndex > 0) {
statement.executeBatch();
List<Integer> generatedKeys = new ArrayList<>(); List<Integer> generatedKeys = new ArrayList<>();
ResultSet resultSet = statement.getGeneratedKeys(); ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) { if (resultSet != null) {
@@ -72,8 +72,4 @@ public class PreparedSQLBatchUpdateActionImpl extends SQLUpdateBatchActionImpl i
return returnedValues; return returnedValues;
} }
@Override
public void executeAsync(Consumer<List<Integer>> success, Consumer<SQLException> failure) {
}
} }
@@ -10,8 +10,8 @@ import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements PreparedSQLUpdateAction { public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements PreparedSQLUpdateAction {
@@ -38,6 +38,17 @@ public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements
return this; return this;
} }
@Override
public PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params) {
if (params == null) {
return setParams((Object[]) null);
} else {
List<Object> paramsList = new ArrayList<>();
params.forEach(paramsList::add);
return setParams(paramsList.toArray());
}
}
@Override @Override
public @NotNull Integer execute() throws SQLException { public @NotNull Integer execute() throws SQLException {
int value = -1; int value = -1;
@@ -48,13 +59,14 @@ public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements
); );
outputDebugMessage(); outputDebugMessage();
if (keyIndex > 0) { if (keyIndex > 0) {
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys(); ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) { if (resultSet != null) {
if (resultSet.next()) value = resultSet.getInt(keyIndex); if (resultSet.next()) value = resultSet.getInt(keyIndex);
resultSet.close(); resultSet.close();
} }
} else { } else {
value = statement.executeUpdate(getSQLContent()); value = statement.executeUpdate();
} }
statement.close(); statement.close();
@@ -63,9 +75,4 @@ public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements
return value; return value;
} }
@Override
public void executeAsync(Consumer<Integer> success, Consumer<SQLException> failure) {
}
} }
@@ -8,7 +8,6 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.function.Consumer;
public class SQLUpdateActionImpl extends AbstractSQLAction<Integer> implements SQLUpdateAction { public class SQLUpdateActionImpl extends AbstractSQLAction<Integer> implements SQLUpdateAction {
@@ -43,10 +42,6 @@ public class SQLUpdateActionImpl extends AbstractSQLAction<Integer> implements S
return returnedValue; return returnedValue;
} }
@Override
public void executeAsync(Consumer<Integer> success, Consumer<SQLException> failure) {
}
@Override @Override
public SQLUpdateActionImpl setKeyIndex(int keyIndex) { public SQLUpdateActionImpl setKeyIndex(int keyIndex) {
@@ -10,7 +10,6 @@ import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> implements SQLUpdateBatchAction { public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> implements SQLUpdateBatchAction {
@@ -24,9 +23,12 @@ public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> i
@Override @Override
public @NotNull String getSQLContent() { public @NotNull String getSQLContent() {
return this.sqlContents.stream() return this.sqlContents.get(0);
.map(content -> "[" + content + "]" + " ") }
.collect(Collectors.joining());
@Override
public @NotNull List<String> getSQLContents() {
return this.sqlContents;
} }
@Override @Override
@@ -51,11 +53,4 @@ public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> i
return returnedValues; return returnedValues;
} }
@Override
public void executeAsync(Consumer<List<Integer>> success, Consumer<SQLException> failure) {
}
} }
@@ -1,6 +1,5 @@
package cc.carm.lib.easysql.action.query; package cc.carm.lib.easysql.action.query;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction; import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import cc.carm.lib.easysql.query.SQLQueryImpl; import cc.carm.lib.easysql.query.SQLQueryImpl;
@@ -37,9 +36,7 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
return setParams((Object[]) null); return setParams((Object[]) null);
} else { } else {
List<Object> paramsList = new ArrayList<>(); List<Object> paramsList = new ArrayList<>();
for (Object param : params) { params.forEach(paramsList::add);
paramsList.add(param);
}
return setParams(paramsList.toArray()); return setParams(paramsList.toArray());
} }
} }
@@ -67,10 +64,4 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
return new SQLQueryImpl(getManager(), this, connection, preparedStatement, resultSet); return new SQLQueryImpl(getManager(), this, connection, preparedStatement, resultSet);
} }
@Override
public void executeAsync(Consumer<SQLQuery> success, Consumer<SQLException> failure) {
}
} }
@@ -1,7 +1,8 @@
package cc.carm.lib.easysql.action.query; package cc.carm.lib.easysql.action.query;
import cc.carm.lib.easysql.action.AbstractSQLAction; import cc.carm.lib.easysql.action.AbstractSQLAction;
import cc.carm.lib.easysql.api.SQLQuery; import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.action.query.QueryAction; import cc.carm.lib.easysql.api.action.query.QueryAction;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import cc.carm.lib.easysql.query.SQLQueryImpl; import cc.carm.lib.easysql.query.SQLQueryImpl;
@@ -11,6 +12,7 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction { public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction {
@@ -20,7 +22,7 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
} }
@Override @Override
public @NotNull SQLQuery execute() throws SQLException { public @NotNull SQLQueryImpl execute() throws SQLException {
Connection connection = getManager().getConnection(); Connection connection = getManager().getConnection();
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@@ -33,8 +35,13 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
return query; return query;
} }
@Override
public void executeAsync(Consumer<SQLQuery> success, Consumer<SQLException> failure) {
@Override
public void executeAsync(Consumer<SQLQuery> success, BiConsumer<SQLException, SQLAction<SQLQuery>> failure) {
try (SQLQueryImpl query = execute()) {
if (success != null) success.accept(query);
} catch (SQLException exception) {
(exceptionHandler == null ? defaultExceptionHandler() : exceptionHandler).accept(exception, this);
}
} }
} }
@@ -13,7 +13,8 @@ import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder implements ConditionalBuilder<T> { public abstract class AbstractConditionalBuilder<B extends ConditionalBuilder<B, T>, T>
extends AbstractSQLBuilder implements ConditionalBuilder<B, T> {
ArrayList<String> conditionSQLs = new ArrayList<>(); ArrayList<String> conditionSQLs = new ArrayList<>();
ArrayList<Object> conditionParams = new ArrayList<>(); ArrayList<Object> conditionParams = new ArrayList<>();
@@ -23,39 +24,41 @@ public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder i
super(manager); super(manager);
} }
protected abstract B getThis();
@Override @Override
public AbstractConditionalBuilder<T> setConditions(@Nullable String condition) { public B setConditions(@Nullable String condition) {
this.conditionSQLs = new ArrayList<>(); this.conditionSQLs = new ArrayList<>();
this.conditionParams = new ArrayList<>(); this.conditionParams = new ArrayList<>();
if (condition != null) this.conditionSQLs.add(condition); if (condition != null) this.conditionSQLs.add(condition);
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> setConditions( public B setConditions(
LinkedHashMap<@NotNull String, @Nullable Object> conditions LinkedHashMap<@NotNull String, @Nullable Object> conditions
) { ) {
conditions.forEach(this::addCondition); conditions.forEach(this::addCondition);
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> addCondition(@Nullable String condition) { public B addCondition(@Nullable String condition) {
this.conditionSQLs.add(condition); this.conditionSQLs.add(condition);
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> addCondition( public B addCondition(
@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue @NotNull String queryName, @NotNull String operator, @Nullable Object queryValue
) { ) {
addCondition("`" + queryName + "` " + operator + " ?"); addCondition("`" + queryName + "` " + operator + " ?");
this.conditionParams.add(queryValue); this.conditionParams.add(queryValue);
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> addCondition( public B addCondition(
@NotNull String[] queryNames, @Nullable Object[] queryValues @NotNull String[] queryNames, @Nullable Object[] queryValues
) { ) {
if (queryNames.length != queryValues.length) { if (queryNames.length != queryValues.length) {
@@ -64,21 +67,21 @@ public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder i
for (int i = 0; i < queryNames.length; i++) { for (int i = 0; i < queryNames.length; i++) {
addCondition(queryNames[i], queryValues[i]); addCondition(queryNames[i], queryValues[i]);
} }
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> addNotNullCondition(@NotNull String queryName) { public B addNotNullCondition(@NotNull String queryName) {
return addCondition("`" + queryName + "` IS NOT NULL"); return addCondition("`" + queryName + "` IS NOT NULL");
} }
@Override @Override
public AbstractConditionalBuilder<T> addTimeCondition( public B addTimeCondition(
@NotNull String queryName, @Nullable Date startDate, @Nullable Date endDate @NotNull String queryName, @Nullable Date startDate, @Nullable Date endDate
) { ) {
if (startDate == null && endDate == null) return this; // 都不限定时间,不用判断了 if (startDate == null && endDate == null) return getThis(); // 都不限定时间,不用判断了
if (startDate != null) { if (startDate != null) {
addCondition("`" + queryName + "` BETWEEN ? AND ?"); addCondition("`" + queryName + "` BETWEEN ? AND ?");
this.conditionParams.add(startDate); this.conditionParams.add(startDate);
@@ -96,14 +99,14 @@ public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder i
} else { } else {
addCondition(queryName, "<=", endDate); addCondition(queryName, "<=", endDate);
} }
return this; return getThis();
} }
@Override @Override
public AbstractConditionalBuilder<T> setLimit(int limit) { public B setLimit(int limit) {
this.limit = limit; this.limit = limit;
return this; return getThis();
} }
protected String buildConditionSQL() { protected String buildConditionSQL() {
@@ -7,7 +7,7 @@ import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class DeleteBuilderImpl public class DeleteBuilderImpl
extends AbstractConditionalBuilder<PreparedSQLUpdateAction> extends AbstractConditionalBuilder<DeleteBuilder, PreparedSQLUpdateAction>
implements DeleteBuilder { implements DeleteBuilder {
String tableName; String tableName;
@@ -39,4 +39,9 @@ public class DeleteBuilderImpl
} }
@Override
protected DeleteBuilderImpl getThis() {
return this;
}
} }
@@ -43,9 +43,4 @@ public abstract class InsertBuilderImpl<T> extends AbstractSQLBuilder implements
public String getTableName() { public String getTableName() {
return tableName; return tableName;
} }
public InsertBuilderImpl<T> setTableName(String tableName) {
this.tableName = tableName;
return this;
}
} }
@@ -16,6 +16,7 @@ public class QueryBuilderImpl extends AbstractSQLBuilder implements QueryBuilder
} }
@Override @Override
@Deprecated
public QueryAction withSQL(@NotNull String sql) { public QueryAction withSQL(@NotNull String sql) {
return new QueryActionImpl(getManager(), sql); return new QueryActionImpl(getManager(), sql);
} }
@@ -43,9 +43,4 @@ public abstract class ReplaceBuilderImpl<T> extends AbstractSQLBuilder implement
public String getTableName() { public String getTableName() {
return tableName; return tableName;
} }
public ReplaceBuilderImpl<T> setTableName(String tableName) {
this.tableName = tableName;
return this;
}
} }
@@ -50,12 +50,6 @@ public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableC
return new SQLUpdateActionImpl(getManager(), createSQL.toString()); return new SQLUpdateActionImpl(getManager(), createSQL.toString());
} }
@Override
public TableCreateBuilder setTableName(@NotNull String tableName) {
this.tableName = tableName;
return this;
}
@Override @Override
public TableCreateBuilder addColumn(@NotNull String column) { public TableCreateBuilder addColumn(@NotNull String column) {
this.columns.add(column); this.columns.add(column);
@@ -5,18 +5,20 @@ import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
import cc.carm.lib.easysql.api.builder.TableQueryBuilder; import cc.carm.lib.easysql.api.builder.TableQueryBuilder;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
public class TableQueryBuilderImpl public class TableQueryBuilderImpl
extends AbstractConditionalBuilder<PreparedQueryAction> extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
implements TableQueryBuilder { implements TableQueryBuilder {
@NotNull String tableName; @NotNull String tableName;
ArrayList<Object> params = new ArrayList<>();
String[] columns; String[] columns;
@Nullable String orderBy;
int[] pageLimit;
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) { public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
super(manager); super(manager);
this.tableName = tableName; this.tableName = tableName;
@@ -42,10 +44,17 @@ public class TableQueryBuilderImpl
sqlBuilder.append("`").append(tableName).append("`"); sqlBuilder.append("`").append(tableName).append("`");
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL()); if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
if (pageLimit != null && pageLimit.length == 2) {
sqlBuilder.append(" LIMIT ").append(pageLimit[0]).append(",").append(pageLimit[1]);
} else if (limit > 0) {
sqlBuilder.append(" ").append(buildLimitSQL());
}
if (orderBy != null) sqlBuilder.append(orderBy);
return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString()) return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString())
.setParams(hasConditionParams() ? params : null); .setParams(hasConditionParams() ? getConditionParams() : null);
} }
@Override @Override
@@ -59,4 +68,20 @@ public class TableQueryBuilderImpl
return this; return this;
} }
@Override
public TableQueryBuilder orderBy(@NotNull String columnName, boolean asc) {
this.orderBy = "ORDER BY `" + columnName + "` " + (asc ? "ASC" : "DESC");
return this;
}
@Override
public TableQueryBuilder setPageLimit(int start, int end) {
this.pageLimit = new int[]{start, end};
return this;
}
@Override
protected TableQueryBuilderImpl getThis() {
return this;
}
} }
@@ -9,7 +9,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
public class UpdateBuilderImpl public class UpdateBuilderImpl
extends AbstractConditionalBuilder<PreparedSQLUpdateAction> extends AbstractConditionalBuilder<UpdateBuilder, PreparedSQLUpdateAction>
implements UpdateBuilder { implements UpdateBuilder {
String tableName; String tableName;
@@ -73,4 +73,8 @@ public class UpdateBuilderImpl
} }
@Override
protected UpdateBuilder getThis() {
return this;
}
} }
@@ -5,10 +5,10 @@ import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
import cc.carm.lib.easysql.action.SQLUpdateActionImpl; import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
import cc.carm.lib.easysql.action.SQLUpdateBatchActionImpl; import cc.carm.lib.easysql.action.SQLUpdateBatchActionImpl;
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.builder.*; import cc.carm.lib.easysql.api.builder.*;
import cc.carm.lib.easysql.builder.impl.*; import cc.carm.lib.easysql.builder.impl.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -19,6 +19,8 @@ import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLManagerImpl implements SQLManager { public class SQLManagerImpl implements SQLManager {
@@ -29,13 +31,21 @@ public class SQLManagerImpl implements SQLManager {
boolean debug = false; boolean debug = false;
protected ExecutorService executorPool;
public SQLManagerImpl(@NotNull DataSource dataSource) { public SQLManagerImpl(@NotNull DataSource dataSource) {
this(dataSource, null); this(dataSource, null);
} }
public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) { public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) {
this.LOGGER = Logger.getLogger("SQLManager" + (name != null ? "#" + name : "")); String managerName = "SQLManager" + (name != null ? "#" + name : "");
this.LOGGER = Logger.getLogger(managerName);
this.dataSource = dataSource; this.dataSource = dataSource;
this.executorPool = Executors.newFixedThreadPool(3, r -> {
Thread thread = new Thread(r, managerName);
thread.setDaemon(true);
return thread;
});
} }
@Override @Override
@@ -56,6 +66,9 @@ public class SQLManagerImpl implements SQLManager {
return LOGGER; return LOGGER;
} }
public ExecutorService getExecutorPool() {
return executorPool;
}
@Override @Override
public @NotNull DataSource getDataSource() { public @NotNull DataSource getDataSource() {
@@ -1,7 +1,7 @@
package cc.carm.lib.easysql.query; package cc.carm.lib.easysql.query;
import cc.carm.lib.easysql.action.query.QueryActionImpl; import cc.carm.lib.easysql.action.query.QueryActionImpl;
import cc.carm.lib.easysql.api.SQLQuery; import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import java.sql.Connection; import java.sql.Connection;
@@ -70,7 +70,7 @@ public class SQLQueryImpl implements SQLQuery {
); );
getManager().getActiveQuery().remove(getAction().getActionUUID()); getManager().getActiveQuery().remove(getAction().getActionUUID());
} catch (SQLException e) { } catch (SQLException e) {
getAction().getExceptionHandler().accept(e); getAction().handleException(e);
} }
this.queryAction = null; this.queryAction = null;
} }
@@ -38,10 +38,9 @@ public class StatementUtil {
) throws SQLException { ) throws SQLException {
sql = sql.trim(); sql = sql.trim();
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
final Map<Integer, Integer> nullTypeMap = new HashMap<>(); Map<Integer, Integer> nullTypeMap = new HashMap<>();
if (params != null) { if (params != null) fillParams(statement, Arrays.asList(params), nullTypeMap);
fillParams(statement, Arrays.asList(params), nullTypeMap); statement.addBatch();
}
return statement; return statement;
} }
@@ -74,7 +73,7 @@ public class StatementUtil {
sql = sql.trim(); sql = sql.trim();
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
final Map<Integer, Integer> nullTypeMap = new HashMap<>(); Map<Integer, Integer> nullTypeMap = new HashMap<>();
for (Object[] params : paramsBatch) { for (Object[] params : paramsBatch) {
fillParams(statement, Arrays.asList(params), nullTypeMap); fillParams(statement, Arrays.asList(params), nullTypeMap);
statement.addBatch(); statement.addBatch();
+39 -15
View File
@@ -4,10 +4,19 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<sonar.organization>carmjos</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
</properties>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<version>v0.0.1</version> <version>0.2.6</version>
<modules> <modules>
<module>easysql-api</module> <module>easysql-api</module>
@@ -15,12 +24,13 @@
<module>easysql-beecp</module> <module>easysql-beecp</module>
<module>easysql-hikaricp</module> <module>easysql-hikaricp</module>
<module>easysql-demo</module>
</modules> </modules>
<name>EasySQL</name> <name>EasySQL</name>
<description>简单便捷的数据库操作工具,可自选连接池。</description> <description>简单便捷的数据库操作工具,可自选连接池。</description>
<url>https://github.com/CarmJos/${name}</url> <url>https://github.com/CarmJos/${project.name}</url>
<developers> <developers>
<developer> <developer>
@@ -28,12 +38,15 @@
<name>Carm Jos</name> <name>Carm Jos</name>
<email>carm@carm.cc</email> <email>carm@carm.cc</email>
<url>https://www.carm.cc</url> <url>https://www.carm.cc</url>
<roles>
<role>Main Developer</role>
</roles>
</developer> </developer>
</developers> </developers>
<scm>
<connection>scm:git:git@github.com:CarmJos/EasySQL.git</connection>
<developerConnection>scm:git:git@github.com:CarmJos/EasySQL.git</developerConnection>
<url>https://github.com/CarmJos/EasySQL</url>
</scm>
<licenses> <licenses>
<license> <license>
<name>GNU General Public License v3.0</name> <name>GNU General Public License v3.0</name>
@@ -51,13 +64,6 @@
<url>${project.url}/actions/workflows/maven.yml</url> <url>${project.url}/actions/workflows/maven.yml</url>
</ciManagement> </ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<repositories> <repositories>
<repository> <repository>
@@ -79,7 +85,7 @@
<repository> <repository>
<id>github</id> <id>github</id>
<name>GitHub Packages</name> <name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/${project.name}</url> <url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
</repository> </repository>
</repositories> </repositories>
@@ -91,7 +97,7 @@
<repository> <repository>
<id>github</id> <id>github</id>
<name>GitHub Packages</name> <name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/${project.name}</url> <url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
</repository> </repository>
</distributionManagement> </distributionManagement>
@@ -122,6 +128,20 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
</plugin> </plugin>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-gpg-plugin</artifactId>-->
<!-- <version>1.5</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>sign-artifacts</id>-->
<!-- <phase>verify</phase>-->
<!-- <goals>-->
<!-- <goal>sign</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
</plugins> </plugins>
<pluginManagement> <pluginManagement>
@@ -136,7 +156,11 @@
<links> <links>
<link>https://javadoc.io/doc/org.jetbrains/annotations/</link> <link>https://javadoc.io/doc/org.jetbrains/annotations/</link>
</links> </links>
<detectJavaApiLink>true</detectJavaApiLink> <detectJavaApiLink>false</detectJavaApiLink>
<encoding>UTF-8</encoding>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
<locale>zh_CN</locale>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>