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

Compare commits

..

24 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
45 changed files with 707 additions and 210 deletions
+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
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
distribution: 'adopt'
- name: Generate docs
run: mvn clean package
run: mvn clean package -DskipTests
- name: Copy to Location
run: |
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
java-version: '11'
distribution: 'adopt'
- name: "Package"
run: mvn -B package --file pom.xml
run: mvn -B package --file pom.xml -Dmaven.javadoc.skip=true
- name: "Target Stage"
run: mkdir staging && cp */target/*.jar staging
- 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
+97 -16
View File
@@ -26,10 +26,6 @@
- 基于JDBC开发,可自选连接池、JDBC驱动。
- 简单便捷的增删改查接口,无需手写SQL语句。
- 额外提供部分常用情况的SQL操作
- 存在则更新,不存在则插入
- 创建表
- 修改表
- ...
- 自动关闭数据流
- 支持同步操作与异步操作
@@ -41,18 +37,43 @@
您可以 [点击这里](easysql-demo/src/main/java/EasySQLDemo.java) 查看部分代码演示,更多演示详见 [开发介绍](.documentation/README.md) 。
### 依赖方式 (Maven)
### 依赖方式
#### Maven 依赖
<details>
<summary>远程库配置</summary>
```xml
<project>
<repositories>
<repository>
<id>github</id>
<!--采用github依赖库,安全稳定,但需要配置 (推荐)-->
<id>EasySQL</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
</repository>
<repository>
<!--采用我的私人依赖库,简单方便,但可能因为变故而无法使用-->
<id>carm-repo</id>
<name>Carm's Repo</name>
<url>https://repo.carm.cc/repository/maven-public/</url>
</repository>
</repositories>
</project>
```
</details>
<details>
<summary>原生依赖</summary>
```xml
<project>
<dependencies>
<!--对于需要提供公共接口的项目,可以仅打包API部分,方便他人调用-->
<dependency>
@@ -70,14 +91,19 @@
<scope>compile</scope>
</dependency>
<!--如需自定义连接池,则可以仅打包实现部分,自行创建SQLManager-->
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-beecp</artifactId>
<version>[LATEST RELEASE]</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
```
</details>
<details>
<summary>含连接池版本</summary>
```xml
<project>
<dependencies>
<!--也可直接选择打包了连接池的版本-->
<dependency>
<groupId>cc.carm.lib</groupId>
@@ -91,12 +117,64 @@
<version>[LATEST VERSION]</version>
<scope>compile</scope>
</dependency>
</dependencies>
</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>
## 支持与捐赠
若您觉得本插件做的不错,您可以通过捐赠支持我!
@@ -108,7 +186,9 @@
## 开源协议
本项目源码采用 [GNU General Public License v3.0](https://opensource.org/licenses/GPL-3.0) 开源协议。
> ### 关于 GPL 协议
<details>
<summary>关于 GPL 协议</summary>
> GNU General Public Licence (GPL) 有可能是开源界最常用的许可模式。GPL 保证了所有开发者的权利,同时为使用者提供了足够的复制,分发,修改的权利:
>
> #### 可自由复制
@@ -123,3 +203,4 @@
> 需要注意的是,分发的时候,需要明确提供源代码和二进制文件,另外,用于某些程序的某些协议有一些问题和限制,你可以看一下 @PierreJoye 写的 Practical Guide to GPL Compliance 一文。使用 GPL 协议,你必须在源代码代码中包含相应信息,以及协议本身。
>
> *以上文字来自 [五种开源协议GPL,LGPL,BSD,MIT,Apache](https://www.oschina.net/question/54100_9455) 。*
</details>
+3 -3
View File
@@ -5,7 +5,7 @@
<parent>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<version>0.2.1</version>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -46,8 +46,8 @@
</ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<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>
</properties>
@@ -1,5 +1,6 @@
package cc.carm.lib.easysql.api;
import cc.carm.lib.easysql.api.function.SQLFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -7,24 +8,21 @@ import java.sql.SQLException;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
*
* <ul>
* <li>同步执行 {@link #execute()}, {@link #execute(Function, BiConsumer)}</li>
* <br> 同步执行方法中有会抛出异常的方法与不抛出异常的方法,
* <br> 若选择不抛出异常,则返回值可能为空,需要特殊处理。
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, BiConsumer)}
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
*
* <li>异步执行 {@link #executeAsync(Consumer, BiConsumer)}</li>
* <br> 异步执行时将提供成功与异常两种处理方式
* <br> 可自行选择是否对数据或异常进行处理
* <br> 默认的异常处理器为 {@link #defaultExceptionHandler()}
* <li>异步执行 {@link #executeAsync(Consumer, BiConsumer)}
* <br>异步执行时将提供成功与异常两种处理方式
* <br>可自行选择是否对数据或异常进行处理
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}</li>
* </ul>
*
* <b>注意:</b> 无论是否异步,都不需要自行关闭ResultSet,本API已自动关闭
*
* @param <T> 需要返回的类型
* @author CarmJos
* @since 0.0.1
@@ -74,20 +72,6 @@ public interface SQLAction<T> {
*/
@NotNull T execute() throws SQLException;
/**
* 执行语句并处理返回值
*
* @param function 处理方法
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
* @param <R> 需要返回的内容
* @return 指定类型数据
*/
@Nullable
default <R> R execute(@NotNull Function<T, R> function, @Nullable BiConsumer<SQLException, SQLAction<T>> exceptionHandler) {
T value = execute(exceptionHandler);
if (value == null) return null;
else return function.apply(value);
}
/**
* 执行语句并返回值
@@ -97,14 +81,44 @@ public interface SQLAction<T> {
*/
@Nullable
default T execute(@Nullable BiConsumer<SQLException, SQLAction<T>> exceptionHandler) {
if (exceptionHandler == null) exceptionHandler = defaultExceptionHandler();
T value = null;
return execute(t -> t, exceptionHandler);
}
/**
* 执行语句并处理返回值
*
* @param function 处理方法
* @param <R> 需要返回的内容
* @return 指定类型数据
* @throws SQLException 当SQL操作出现问题时抛出
*/
@Nullable
default <R> R executeFunction(@NotNull SQLFunction<T, R> function) throws SQLException {
try {
value = execute();
T value = execute();
return function.apply(value);
} catch (SQLException exception) {
exceptionHandler.accept(exception, this);
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;
}
return value;
}
/**
@@ -131,6 +145,12 @@ public interface SQLAction<T> {
*/
void executeAsync(@Nullable Consumer<T> success, @Nullable BiConsumer<SQLException, SQLAction<T>> failure);
default void handleException(@Nullable BiConsumer<SQLException, SQLAction<T>> handler, SQLException exception) {
if (handler == null) handler = defaultExceptionHandler();
handler.accept(exception, this);
}
/**
* @return 默认的异常处理器
*/
@@ -138,6 +158,7 @@ public interface SQLAction<T> {
return (exception, action) -> {
getManager().getLogger().severe("Error when execute [" + action.getSQLContent() + "]");
getManager().getLogger().severe(exception.getLocalizedMessage());
exception.printStackTrace();
};
}
@@ -4,8 +4,8 @@ import org.jetbrains.annotations.NotNull;
/**
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
* <br> 其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
* <br> 也是本接口的核心功能所在
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
* <br>也是本接口的核心功能所在
*
* @author CarmJos
*/
@@ -2,6 +2,8 @@ package cc.carm.lib.easysql.api;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
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 org.jetbrains.annotations.NotNull;
@@ -34,6 +36,7 @@ public interface SQLManager {
* 得到一个数据库连接实例
*
* @return Connection
* @throws SQLException 见 {@link DataSource#getConnection()}
*/
@NotNull Connection getConnection() throws SQLException;
@@ -46,34 +49,43 @@ public interface SQLManager {
/**
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
* 该方法使用 Statement 实现,请注意SQL注入风险!
*
* @param sql SQL语句内容
* @return 更新的行数
* @see SQLUpdateAction
*/
@Nullable Integer executeSQL(String sql);
/**
* 执行一条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
*
* @param sql SQL语句内容
* @param sql SQL语句内容
* @param params SQL语句中 ? 的对应参数
* @return 更新的行数
* @see PreparedSQLUpdateAction
*/
@Nullable Integer executeSQL(String sql, Object[] params);
/**
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
*
* @param sql SQL语句内容
* @param sql SQL语句内容
* @param paramsBatch SQL语句中对应?的参数组
* @return 对应参数返回的行数
* @see PreparedSQLUpdateBatchAction
*/
@Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
/**
* 执行多条不需要返回结果的SQL。
* 该方法使用 Statement 实现,请注意SQL注入风险!
*
* @param sql SQL语句内容
* @param sql SQL语句内容
* @param moreSQL 更多SQL语句内容
* @return 对应参数返回的行数
* @see SQLUpdateBatchAction
*/
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
@@ -85,20 +97,67 @@ public interface SQLManager {
*/
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
/**
* 在库中创建一个表
*
* @param tableName 表名
* @return {@link TableCreateBuilder}
*/
TableCreateBuilder createTable(@NotNull String tableName);
/**
* 新建一个查询
*
* @return {@link QueryBuilder}
*/
QueryBuilder createQuery();
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
/**
* 创建一条插入操作
*
* @param tableName 目标表名
* @return {@link InsertBuilder}
*/
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);
/**
* 创建支持多组数据的替换操作
*
* @param tableName 目标表名
* @return {@link ReplaceBuilder}
*/
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
/**
* 创建更新操作
*
* @param tableName 目标表名
* @return {@link UpdateBuilder}
*/
UpdateBuilder createUpdate(@NotNull String tableName);
/**
* 创建删除操作
*
* @param tableName 目标表名
* @return {@link DeleteBuilder}
*/
DeleteBuilder createDelete(@NotNull String tableName);
}
@@ -26,8 +26,8 @@ public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* 若该值 > 0,则 {@link #execute()} 返回自增主键数值
* 若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex);
@@ -2,14 +2,18 @@ package cc.carm.lib.easysql.api.action;
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> {
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* 若该值 > 0,则 {@link #execute()} 返回自增主键数值
* 若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link SQLUpdateAction}
*/
SQLUpdateAction setKeyIndex(int keyColumnIndex);
@@ -23,4 +27,6 @@ public interface SQLUpdateAction extends SQLAction<Integer> {
return setKeyIndex(-1); // will return changed lines number
}
}
@@ -3,7 +3,9 @@ package cc.carm.lib.easysql.api.action;
import cc.carm.lib.easysql.api.SQLAction;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.List;
import java.util.function.BiConsumer;
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
@@ -15,4 +17,20 @@ public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
*/
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();
};
}
}
@@ -1,7 +1,51 @@
package cc.carm.lib.easysql.api.action.query;
import cc.carm.lib.easysql.api.SQLAction;
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> {
/**
* 执行语句并处理返回值
*
* @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);
}
}
}
@@ -7,36 +7,36 @@ import org.jetbrains.annotations.Nullable;
import java.util.Date;
import java.util.LinkedHashMap;
public interface ConditionalBuilder<T> extends SQLBuilder {
public interface ConditionalBuilder<B extends ConditionalBuilder<B, T>, T> extends SQLBuilder {
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);
}
ConditionalBuilder<T> addCondition(@NotNull String[] queryNames, @Nullable Object[] queryValues);
B addCondition(@NotNull String[] queryNames, @Nullable Object[] queryValues);
ConditionalBuilder<T> addNotNullCondition(@NotNull String queryName);
default ConditionalBuilder<T> addTimeCondition(@NotNull String queryName, long startMillis, long endMillis) {
B addNotNullCondition(@NotNull String queryName);
default B addTimeCondition(@NotNull String queryName, long startMillis, long endMillis) {
return addTimeCondition(queryName,
startMillis > 0 ? new Date(startMillis) : 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;
public interface DeleteBuilder extends ConditionalBuilder<PreparedSQLUpdateAction> {
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, PreparedSQLUpdateAction> {
String getTableName();
@@ -7,8 +7,6 @@ public interface InsertBuilder<T> {
String getTableName();
InsertBuilder<T> setTableName(String tableName);
T setColumnNames(List<String> columnNames);
default T setColumnNames(String... columnNames) {
@@ -8,11 +8,12 @@ import org.jetbrains.annotations.NotNull;
public interface QueryBuilder extends SQLBuilder {
/**
* 通过一条 SQL语句创建查询
* 通过一条 SQL语句创建查询
* 该方法使用 Statement 实现,请注意SQL注入风险!
*
* @param sql SQL语句
* @return {@link QueryAction}
* @deprecated 存在SQL注入风险,使用 {@link QueryBuilder#withPreparedSQL(String)}
* @deprecated 存在SQL注入风险,建议使用 {@link QueryBuilder#withPreparedSQL(String)}
*/
@Deprecated
QueryAction withSQL(@NotNull String sql);
@@ -7,8 +7,6 @@ public interface ReplaceBuilder<T> {
String getTableName();
ReplaceBuilder<T> setTableName(String tableName);
T setColumnNames(List<String> columnNames);
default T setColumnNames(String... columnNames) {
@@ -8,8 +8,6 @@ public interface TableCreateBuilder extends SQLBuilder {
@NotNull String getTableName();
TableCreateBuilder setTableName(@NotNull String tableName);
@NotNull String getTableSettings();
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 org.jetbrains.annotations.NotNull;
public interface TableQueryBuilder extends ConditionalBuilder<PreparedQueryAction> {
public interface TableQueryBuilder extends ConditionalBuilder<TableQueryBuilder, PreparedQueryAction> {
@NotNull String getTableName();
/**
* 选定用于查询的列名
*
* @param columnNames 列名
* @return {@link TableQueryBuilder}
*/
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;
public interface UpdateBuilder extends ConditionalBuilder<PreparedSQLUpdateAction> {
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, PreparedSQLUpdateAction> {
String getTableName();
@@ -1,4 +1,9 @@
package cc.carm.lib.easysql.api.builder;
public interface UpsertBuilder {
String getTableName();
UpsertBuilder setColumnNames(String[] columnNames, String updateColumn);
}
@@ -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;
}
+31 -4
View File
@@ -5,14 +5,14 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.2.1</version>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>easysql-beecp</artifactId>
<packaging>jar</packaging>
<name>10-EasySQL-BeeCP</name>
<name>12-EasySQL-BeeCP</name>
<description>EasySQL的应用部分。此为BeeCP版本。</description>
<url>https://github.com/CarmJos/EasySQL</url>
@@ -46,8 +46,8 @@
</ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<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>
@@ -67,6 +67,7 @@
<groupId>com.github.chris2018998</groupId>
<artifactId>beecp</artifactId>
<version>3.3.0</version>
<optional>true</optional>
<scope>compile</scope>
</dependency>
@@ -89,6 +90,32 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<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>
</plugins>
</build>
@@ -1,5 +1,8 @@
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 cn.beecp.BeeDataSource;
import cn.beecp.BeeDataSourceConfig;
@@ -18,4 +21,26 @@ public class EasySQL {
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());
}
}
+3 -3
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.2.1</version>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -46,8 +46,8 @@
</ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<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>
+2 -7
View File
@@ -49,16 +49,11 @@ public class EasySQLDemo {
.build().execute(query -> {
//可以直接进行数据处理
ResultSet result = query.getResultSet();
try {
if (result != null && result.next()) {
return UUIDUtil.toUUID(result.getString("uuid"));
}
} catch (SQLException ignored) {
}
return null;
return result.next() ? UUIDUtil.toUUID(result.getString("uuid")) : null;
}, (exception, action) -> {
// 处理异常,不想处理直接填null
});
}
public void sqlQueryAsync(SQLManager sqlManager) {
+30 -3
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.2.1</version>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -45,8 +45,8 @@
</ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<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>
@@ -66,6 +66,7 @@
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
<optional>true</optional>
<scope>compile</scope>
</dependency>
@@ -88,6 +89,32 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<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>
</plugins>
</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));
}
}
+3 -3
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.2.1</version>
<version>0.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -46,8 +46,8 @@
</ciManagement>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<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>
@@ -12,10 +12,9 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class PreparedSQLBatchUpdateActionImpl extends SQLUpdateBatchActionImpl implements PreparedSQLUpdateBatchAction {
public class PreparedSQLBatchUpdateActionImpl extends AbstractSQLAction<List<Integer>> implements PreparedSQLUpdateBatchAction {
int keyIndex = -1;
List<Object[]> allParams;
@@ -54,6 +53,7 @@ public class PreparedSQLBatchUpdateActionImpl extends SQLUpdateBatchActionImpl i
);
outputDebugMessage();
if (keyIndex > 0) {
statement.executeBatch();
List<Integer> generatedKeys = new ArrayList<>();
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) {
@@ -59,13 +59,14 @@ public class PreparedSQLUpdateActionImpl extends SQLUpdateActionImpl implements
);
outputDebugMessage();
if (keyIndex > 0) {
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet != null) {
if (resultSet.next()) value = resultSet.getInt(keyIndex);
resultSet.close();
}
} else {
value = statement.executeUpdate(getSQLContent());
value = statement.executeUpdate();
}
statement.close();
@@ -8,7 +8,6 @@ import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Consumer;
public class SQLUpdateActionImpl extends AbstractSQLAction<Integer> implements SQLUpdateAction {
@@ -23,9 +23,12 @@ public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> i
@Override
public @NotNull String getSQLContent() {
return this.sqlContents.stream()
.map(content -> "[" + content + "]" + " ")
.collect(Collectors.joining());
return this.sqlContents.get(0);
}
@Override
public @NotNull List<String> getSQLContents() {
return this.sqlContents;
}
@Override
@@ -50,5 +53,4 @@ public class SQLUpdateBatchActionImpl extends AbstractSQLAction<List<Integer>> i
return returnedValues;
}
}
@@ -13,7 +13,8 @@ import java.util.Date;
import java.util.Iterator;
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<Object> conditionParams = new ArrayList<>();
@@ -23,39 +24,41 @@ public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder i
super(manager);
}
protected abstract B getThis();
@Override
public AbstractConditionalBuilder<T> setConditions(@Nullable String condition) {
public B setConditions(@Nullable String condition) {
this.conditionSQLs = new ArrayList<>();
this.conditionParams = new ArrayList<>();
if (condition != null) this.conditionSQLs.add(condition);
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> setConditions(
public B setConditions(
LinkedHashMap<@NotNull String, @Nullable Object> conditions
) {
conditions.forEach(this::addCondition);
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> addCondition(@Nullable String condition) {
public B addCondition(@Nullable String condition) {
this.conditionSQLs.add(condition);
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> addCondition(
public B addCondition(
@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue
) {
addCondition("`" + queryName + "` " + operator + " ?");
this.conditionParams.add(queryValue);
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> addCondition(
public B addCondition(
@NotNull String[] queryNames, @Nullable Object[] queryValues
) {
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++) {
addCondition(queryNames[i], queryValues[i]);
}
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> addNotNullCondition(@NotNull String queryName) {
public B addNotNullCondition(@NotNull String queryName) {
return addCondition("`" + queryName + "` IS NOT NULL");
}
@Override
public AbstractConditionalBuilder<T> addTimeCondition(
public B addTimeCondition(
@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) {
addCondition("`" + queryName + "` BETWEEN ? AND ?");
this.conditionParams.add(startDate);
@@ -96,14 +99,14 @@ public abstract class AbstractConditionalBuilder<T> extends AbstractSQLBuilder i
} else {
addCondition(queryName, "<=", endDate);
}
return this;
return getThis();
}
@Override
public AbstractConditionalBuilder<T> setLimit(int limit) {
public B setLimit(int limit) {
this.limit = limit;
return this;
return getThis();
}
protected String buildConditionSQL() {
@@ -7,7 +7,7 @@ import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull;
public class DeleteBuilderImpl
extends AbstractConditionalBuilder<PreparedSQLUpdateAction>
extends AbstractConditionalBuilder<DeleteBuilder, PreparedSQLUpdateAction>
implements DeleteBuilder {
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() {
return tableName;
}
public InsertBuilderImpl<T> setTableName(String tableName) {
this.tableName = tableName;
return this;
}
}
@@ -43,9 +43,4 @@ public abstract class ReplaceBuilderImpl<T> extends AbstractSQLBuilder implement
public String getTableName() {
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());
}
@Override
public TableCreateBuilder setTableName(@NotNull String tableName) {
this.tableName = tableName;
return this;
}
@Override
public TableCreateBuilder addColumn(@NotNull String 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.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import org.jetbrains.annotations.Nullable;
public class TableQueryBuilderImpl
extends AbstractConditionalBuilder<PreparedQueryAction>
extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
implements TableQueryBuilder {
@NotNull String tableName;
ArrayList<Object> params = new ArrayList<>();
String[] columns;
@Nullable String orderBy;
int[] pageLimit;
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
super(manager);
this.tableName = tableName;
@@ -42,10 +44,17 @@ public class TableQueryBuilderImpl
sqlBuilder.append("`").append(tableName).append("`");
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())
.setParams(hasConditionParams() ? params : null);
.setParams(hasConditionParams() ? getConditionParams() : null);
}
@Override
@@ -59,4 +68,20 @@ public class TableQueryBuilderImpl
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.*;
public class UpdateBuilderImpl
extends AbstractConditionalBuilder<PreparedSQLUpdateAction>
extends AbstractConditionalBuilder<UpdateBuilder, PreparedSQLUpdateAction>
implements UpdateBuilder {
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.SQLUpdateBatchActionImpl;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.action.query.SQLQuery;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
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.builder.impl.*;
import org.jetbrains.annotations.NotNull;
@@ -1,7 +1,5 @@
package cc.carm.lib.easysql.util;
import cc.carm.lib.easysql.api.SQLAction;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
@@ -40,10 +38,9 @@ public class StatementUtil {
) throws SQLException {
sql = sql.trim();
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
final Map<Integer, Integer> nullTypeMap = new HashMap<>();
if (params != null) {
fillParams(statement, Arrays.asList(params), nullTypeMap);
}
Map<Integer, Integer> nullTypeMap = new HashMap<>();
if (params != null) fillParams(statement, Arrays.asList(params), nullTypeMap);
statement.addBatch();
return statement;
}
@@ -76,7 +73,7 @@ public class StatementUtil {
sql = sql.trim();
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) {
fillParams(statement, Arrays.asList(params), nullTypeMap);
statement.addBatch();
+38 -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">
<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>
<artifactId>easysql-parent</artifactId>
<packaging>pom</packaging>
<version>0.2.1</version>
<version>0.2.6</version>
<modules>
<module>easysql-api</module>
@@ -21,7 +30,7 @@
<name>EasySQL</name>
<description>简单便捷的数据库操作工具,可自选连接池。</description>
<url>https://github.com/CarmJos/${name}</url>
<url>https://github.com/CarmJos/${project.name}</url>
<developers>
<developer>
@@ -29,12 +38,15 @@
<name>Carm Jos</name>
<email>carm@carm.cc</email>
<url>https://www.carm.cc</url>
<roles>
<role>Main Developer</role>
</roles>
</developer>
</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>
<license>
<name>GNU General Public License v3.0</name>
@@ -52,13 +64,6 @@
<url>${project.url}/actions/workflows/maven.yml</url>
</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>
<repository>
@@ -123,8 +128,22 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</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>
<pluginManagement>
<plugins>
@@ -137,7 +156,11 @@
<links>
<link>https://javadoc.io/doc/org.jetbrains/annotations/</link>
</links>
<detectJavaApiLink>true</detectJavaApiLink>
<detectJavaApiLink>false</detectJavaApiLink>
<encoding>UTF-8</encoding>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
<locale>zh_CN</locale>
</configuration>
<executions>
<execution>
@@ -231,4 +254,4 @@
</build>
</project>
</project>