Compare commits

..

No commits in common. "master" and "v1.4.5" have entirely different histories.

389 changed files with 4910 additions and 27277 deletions

View File

@ -1,45 +0,0 @@
name: 错误报告
description: File a bug report.
title: "[错误报告]: 描述"
labels: [""]
body:
- type: markdown
attributes:
value: |
请确认以下信息:
1. 请按此模板提交issues, 不按模板提交的问题将直接关闭
2. 如果你的问题与该仓库无关或者可以直接在以往 issue 中找到, 那么你的 issue 将会被直接关闭
3. 提交问题务必描述清楚、附上日志, 描述不清导致无法理解和分析的问题会被直接关闭
- type: checkboxes
id: confirm
attributes:
label: 确认
description: 在提交 issue 之前,请确认你已经阅读并确认以下内容
options:
- label: 我的版本是最新版本, 我的版本号与 [version](https://central.sonatype.com/search?q=g:com.github.yulichang%20%20a:mybatis-plus-join-boot-starter&smo=true) 相同, 并且项目里无依赖冲突
required: true
- label: 我已经在 [issue](https://github.com/yulichang/mybatis-plus-join/issues) 中搜索过, 确认问题没有被提出过
required: true
- label: 我已经修改标题, 将标题中的 描述 替换为遇到的问题
required: true
- type: input
id: version
attributes:
label: 当前程序版本
description: 遇到问题时程序所在的版本号
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: 问题描述
description: 请详细描述你碰到的问题
placeholder: "问题描述"
validations:
required: true
- type: textarea
id: logs
attributes:
label: 详细堆栈日志
description: 问题出现时,程序错误堆栈日志。
render: bash

View File

@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: 官网
url: https://mybatis-plus-join.github.io/
about: document.

View File

@ -1,35 +0,0 @@
name: 功能改进
description: Feature Request
title: "[功能改进]: 描述"
labels: [""]
body:
- type: markdown
attributes:
value: |
请说明你希望添加的功能。
- type: checkboxes
id: confirm
attributes:
label: 确认
description: 在提交 issue 之前,请确认你已经阅读并确认以下内容
options:
- label: 我的版本是最新版本, 我的版本号与 [version](https://central.sonatype.com/search?q=g:com.github.yulichang%20%20a:mybatis-plus-join-boot-starter&smo=true) 相同, 并且项目里无依赖冲突
required: true
- label: 我已经在 [issue](https://github.com/yulichang/mybatis-plus-join/issues) 中搜索过, 确认问题没有被提出过
required: true
- label: 我已经修改标题, 将标题中的 描述 替换为遇到的问题
required: true
- type: textarea
id: feature-request
attributes:
label: 功能改进
description: 请详细描述需要改进或者添加的功能。
placeholder: "功能改进"
validations:
required: true
- type: textarea
id: references
attributes:
label: 参考资料
description: 可以列举一些参考资料,但是不要引用同类但商业化软件的任何内容。
placeholder: "参考资料"

View File

@ -1,13 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "maven" # See documentation for possible values
directory: "/"
schedule:
interval: "weekly"
ignore:
- dependency-name: "com.baomidou:mybatis-plus*"

View File

@ -1,39 +0,0 @@
name: Maven Package
on:
push:
tags:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
- name: Build with Maven
run: mvn -B package --file pom.xml
- name: Set up Apache Maven Central
uses: actions/setup-java@v4
with: # running setup-java again overwrites the settings.xml
distribution: 'temurin'
java-version: '17'
server-id: maven # Value of the distributionManagement/repository/id field of the pom.xml
server-username: MAVEN_USERNAME # env variable for username in deploy
server-password: MAVEN_CENTRAL_TOKEN # env variable for token in deploy
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- name: Publish to Apache Maven Central
run: mvn com.github.yulichang:pom-maven-plugin:pom && mvn clean deploy
env:
MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
MAVEN_CENTRAL_TOKEN: ${{ secrets.MAVEN_CENTRAL_TOKEN }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}

View File

@ -1,31 +0,0 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
# 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.
name: Java CI with Maven
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn -B package --file pom.xml

View File

@ -1,39 +0,0 @@
name: Maven Package
on:
push:
branches:
- snapshot
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
- name: Build with Maven
run: mvn -B package --file pom.xml
- name: Set up Apache Maven Central
uses: actions/setup-java@v4
with: # running setup-java again overwrites the settings.xml
distribution: 'temurin'
java-version: '17'
server-id: maven # Value of the distributionManagement/repository/id field of the pom.xml
server-username: MAVEN_USERNAME # env variable for username in deploy
server-password: MAVEN_CENTRAL_TOKEN # env variable for token in deploy
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- name: Publish to Apache Maven Central
run: mvn com.github.yulichang:pom-maven-plugin:pom -Dprofile=snapshot && mvn clean deploy
env:
MAVEN_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
MAVEN_CENTRAL_TOKEN: ${{ secrets.MAVEN_CENTRAL_TOKEN }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}

113
MAPPING.md Normal file
View File

@ -0,0 +1,113 @@
# mybatis-plus-join
#### @EntityMapping@FieldMapping 注解
UserDO.java
```java
@Data
@TableName("user")
public class UserDO {
@TableId
private Integer id;
private Integer pid;//父id
/* 其他属性略 */
/**
* 查询上级 一对一
*/
@TableField(exist = false)
@EntityMapping(thisField = "pid", joinField = "id")
private UserDO pUser;
/**
* 查询下级 一对多
*/
@TableField(exist = false)
@EntityMapping(thisField = "id", joinField = "pid")
private List<UserDO> childUser;
/**
* 带条件的查询下级 一对多
*/
@TableField(exist = false)
@EntityMapping(thisField = "id", joinField = "pid",
condition = {
@MPJMappingCondition(column = "sex", value = "0"),//sex = '0' 默认条件是等于
@MPJMappingCondition(column = "name", value = "张三", keyWord = SqlKeyword.LIKE)//name like '%a%'
},
apply = @MPJMappingApply(value = "id between 1 and 20"))//拼接sql 同 wrapper.apply()
private List<UserDO> childUserCondition;
/**
* 查询地址 (一对多)
*/
@TableField(exist = false)
@EntityMapping(thisField = "id", joinField = "userId")
private List<UserAddressDO> addressList;
/**
* 绑定字段 (一对多)
*/
@TableField(exist = false)
@FieldMapping(tag = UserDO.class, thisField = "id", joinField = "pid", select = "id")
private List<Integer> childIds;
}
```
使用
```java
/**
* 一对一,一对多关系映射查询
* 如果不需要关系映射就使用mybatis plus原生方法即可比如 getById listByIds 等
* <p>
* 注意关系映射不会去关联查询而是执行多次单表查询对结果汇总后使用in语句查询,再对结果进行匹配)
*/
@SpringBootTest
class MappingTest {
@Resource
private UserMapper userMapper;
@Test
void test1() {
UserDO deep = userMapper.selectByIdDeep(2);
System.out.println(deep);
}
@Test
void test2() {
List<UserDO> list = userMapper.selectRelation(mapper -> mapper.selectList(Wrappers.emptyWrapper()));
list.forEach(System.out::println);
}
@Test
void test3() {
Page<UserDO> page = new Page<>(2, 2);
Page<UserDO> result = userMapper.selectRelation(mapper -> mapper.selectPage(page, Wrappers.emptyWrapper()));
result.getRecords().forEach(System.out::println);
}
/*
更多方法请查阅 MPJDeepMapper 或者 MPJDeepService
使用方式与 mybatis plus 一致
*/
}
```
MPJMapping 说明:
* @EntityMapping / @FieldMapping tag 关联实体类
* @EntityMapping / @FieldMapping thisField 当前类关联对应的字段的属性名,可以不填,默认为当前类的主键
* @EntityMapping / @FieldMapping joinField 关联类对应的字段的属性名,可以不填,默认为关联类的主键
* @EntityMapping / @FieldMapping isThrowExp 一对一查询时,如果查询到多条记录是否抛出异常,true:抛出异常,false:获取列表第一条数据
*
更多功能请看代码注释 [EntityMapping](https://gitee.com/best_handsome/mybatis-plus-join/blob/master/src/main/java/com/github/yulichang/annotation/EntityMapping.java)
[FieldMapping](https://gitee.com/best_handsome/mybatis-plus-join/blob/master/src/main/java/com/github/yulichang/annotation/FieldMapping.java)

View File

@ -1,119 +0,0 @@
<!--suppress HtmlDeprecatedAttribute -->
<p align="center">
<a href="https://github.com/yulichang/mybatis-plus-join" target="_blank">
<img alt="Mybatis-Plus-Join-Logo" src="https://foruda.gitee.com/images/1714756037858567246/8b0258f5_2020985.png">
</a>
</p>
<h1 align="center">MyBatis-Plus-Join</h1>
<p align="center">
为简化开发工作、提高生产率而生
</p>
<p align="center">
<a href="https://central.sonatype.com/artifact/com.github.yulichang/mybatis-plus-join-boot-starter">
<img alt="Maven central" src="https://img.shields.io/maven-central/v/com.github.yulichang/mybatis-plus-join-boot-starter.svg?style=flat-square">
</a>
<a href="https://www.apache.org/licenses/LICENSE-2.0">
<img alt="code style" src="https://img.shields.io/badge/license-Apache%202-4EB1BA.svg?style=flat-square">
</a>
<a href="https://github.com/yulichang/mybatis-plus-join" target="_blank">
<img src="https://img.shields.io/github/stars/yulichang/mybatis-plus-join.svg?style=social&label=Stars" alt=""/>
</a>
<a href="https://gitee.com/best_handsome/mybatis-plus-join" target="_blank">
<img src="https://gitee.com/best_handsome/mybatis-plus-join/badge/star.svg?theme=dark" alt=""/>
</a>
</p>
<p align="center">
<a href="https://gitee.com/baomidou/mybatis-plus" target="_blank">MyBatis-Plus</a> 多表查询的扩展 |
<a href="https://gitee.com/best_handsome/mybatis-plus-join-demo" target="_blank">演示工程</a> |
<a href="https://mybatis-plus-join.github.io" target="_blank">使用文档</a> |
点个Star支持一下吧 (☆▽☆)
</p>
<p align="center">
<a href="https://gitee.com/best_handsome/mybatis-plus-join/issues/I65N2M" target="_blank">添加作者微信备注MPJ加入微信群</a>
<br/>
<img width="200px" height="200px" src="https://foruda.gitee.com/images/1714756135330585984/bcc86eb0_2020985.png" alt="添加作者微信备注MPJ加入微信群"/>
</p>
### <a href="https://mybatis-plus-join.github.io" target="_blank">使用文档WIKI</a>
## 使用方法
### 安装
- Maven
```xml
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<version>1.5.4</version>
</dependency>
```
- Gradle
```
implementation 'com.github.yulichang:mybatis-plus-join-boot-starter:1.5.4'
```
或者clone代码到本地执行 `mvn install`, 再引入以上依赖
<br>
注意: MyBatis Plus版本需要3.1.2+
<br>
### 使用
* mapper继承MPJBaseMapper
### Lambda形式用法MPJLambdaWrapper
#### 简单的连表查询
```java
class test {
@Resource
private UserMapper userMapper;
void testJoin() {
//和Mybatis plus一致MPJLambdaWrapper的泛型必须是主表的泛型并且要用主表的Mapper来调用
MPJLambdaWrapper<UserDO> wrapper = JoinWrappers.lambda(UserDO.class)
.selectAll(UserDO.class)//查询user表全部字段
.select(UserAddressDO::getTel)//查询user_address tel 字段
.selectAs(UserAddressDO::getAddress, UserDTO::getUserAddress)//别名
.select(AreaDO::getProvince, AreaDO::getCity)
.leftJoin(UserAddressDO.class, UserAddressDO::getUserId, UserDO::getId)
.leftJoin(AreaDO.class, AreaDO::getId, UserAddressDO::getAreaId)
.eq(UserDO::getId, 1)
.like(UserAddressDO::getTel, "1")
.gt(UserDO::getId, 5);
//连表查询 返回自定义ResultType
List<UserDTO> list = userMapper.selectJoinList(UserDTO.class, wrapper);
//分页查询 (需要启用 mybatis plus 分页插件)
Page<UserDTO> listPage = userMapper.selectJoinPage(new Page<>(2, 10), UserDTO.class, wrapper);
}
}
```
对应sql
```
SELECT
t.id, t.name, t.sex, t.head_img,
t1.tel, t1.address AS userAddress,
t2.province, t2.city
FROM
user t
LEFT JOIN user_address t1 ON t1.user_id = t.id
LEFT JOIN area t2 ON t2.id = t1.area_id
WHERE (
t.id = ?
AND t1.tel LIKE ?
AND t.id > ?)
```
# <a href="https://mybatis-plus-join.github.io" target="_blank">完整使用文档 wiki</a>
# 用爱发电
<a href="https://mybatis-plus-join.github.io/pages/quickstart/support.html" target="_blank">
<img alt="支持一下mybatis-plus-join" src="https://foruda.gitee.com/images/1717191488951888381/8463cfcd_2020985.png">
</a>

View File

@ -1,41 +1,44 @@
<!--suppress HtmlDeprecatedAttribute -->
<p align="center">
<a href="https://github.com/yulichang/mybatis-plus-join" target="_blank">
<img alt="Mybatis-Plus-Join-Logo" src="https://github.com/yulichang/mybatis-plus-join/assets/33247410/f61a92d0-dc6e-463d-b431-61f469bd35f8">
<img alt="Mybatis-Plus-Join-Logo" src="https://mybatisplusjoin.com/lg.png">
</a>
</p>
<h1 align="center">MyBatis-Plus-Join</h1>
<p align="center">
为简化开发工作、提高生产率而生
</p>
<p align="center">
<a href="https://central.sonatype.com/artifact/com.github.yulichang/mybatis-plus-join-boot-starter">
<img alt="Maven central" src="https://img.shields.io/maven-central/v/com.github.yulichang/mybatis-plus-join-boot-starter.svg?style=flat-square">
</a>
<a href="https://www.apache.org/licenses/LICENSE-2.0">
<img alt="code style" src="https://img.shields.io/badge/license-Apache%202-4EB1BA.svg?style=flat-square">
</a>
<a href="https://github.com/yulichang/mybatis-plus-join" target="_blank">
<img src="https://img.shields.io/github/stars/yulichang/mybatis-plus-join.svg?style=social&label=Stars" alt=""/>
</a>
<a href="https://gitee.com/best_handsome/mybatis-plus-join" target="_blank">
<img src="https://gitee.com/best_handsome/mybatis-plus-join/badge/star.svg?theme=dark" alt=""/>
</a>
<br/>
<a href="https://central.sonatype.com/artifact/com.github.yulichang/mybatis-plus-join-boot-starter">
<img alt="maven" src="https://img.shields.io/maven-central/v/com.github.yulichang/mybatis-plus-join-boot-starter.svg?style=flat-square">
</a>
<a href="https://www.apache.org/licenses/LICENSE-2.0">
<img alt="code style" src="https://img.shields.io/badge/license-Apache%202-4EB1BA.svg?style=flat-square">
</a>
</p>
<h1 align="center">mybatis-plus-join</h1>
<p align="center">
<a href="https://github.com/baomidou/mybatis-plus" target="_blank">MyBatis-Plus</a> 多表查询的扩展 |
<a href="https://github.com/yulichang/mybatis-plus-join-demo" target="_blank">演示工程</a> |
<a href="https://mybatis-plus-join.github.io" target="_blank">使用文档</a> |
<a href="https://gitee.com/baomidou/mybatis-plus" target="_blank">mybatis-plus</a> 多表查询的扩展 |
<a href="https://gitee.com/best_handsome/mybatis-plus-join-demo" target="_blank">演示工程</a> |
<a href="https://www.baidu.com/link?url=wdmhssysW-Mj19Gkcc2CBOzNVoimHat57mlnH78SEU_6y0awYgDKTBy7es9BXnAH&wd=&eqid=908484020001866e000000056440b5e3" target="_blank">使用文档</a> |
点个Star支持一下吧 (☆▽☆)
</p>
<p align="center">
<a href="https://gitee.com/best_handsome/mybatis-plus-join/issues/I65N2M" target="_blank">添加作者微信备注MPJ加入微信群</a>
QQ群:1022221898 或者
<a href="https://gitee.com/best_handsome/mybatis-plus-join/issues/I65N2M" target="_blank">添加作者微信备注MPJ加入微信群</a>
<br/>
<img width="200px" height="200px" src="https://github.com/yulichang/mybatis-plus-join/assets/33247410/6a2aedfa-c67d-4691-9441-204f28b6c73d" alt="添加作者微信备注MPJ加入微信群"/>
<img width="200px" src="https://mybatisplusjoin.com/qr.png" alt="添加作者微信备注MPJ加入微信群"/>
</p>
### <a href="https://mybatis-plus-join.github.io" target="_blank">使用文档WIKI</a>
### <a href="https://www.baidu.com/link?url=6NtKqbGKUIIdwoBUaqNkQnLiG3d5y03L6Pfg6ODId0VKfPifpB1xqdQzsBprm-0h&wd=&eqid=d26e7f1600004777000000056440ade6" target="_blank">使用文档WIKI</a>
## 使用方法
@ -46,21 +49,23 @@
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<version>1.5.4</version>
<version>1.4.5</version>
</dependency>
```
- Gradle
```
implementation 'com.github.yulichang:mybatis-plus-join-boot-starter:1.5.4'
implementation 'com.github.yulichang:mybatis-plus-join-boot-starter:1.4.5'
```
或者clone代码到本地执行 `mvn install`, 再引入以上依赖
或者clone代码到本地执行 mvn install, 再引入以上依赖
<br>
注意: MyBatis Plus版本需要3.1.2+
注意: mybatis plus version >= 3.3.0
<br>
### 使用
* mapper继承MPJBaseMapper
* mapper继承MPJBaseMapper (必选)
* service继承MPJBaseService (可选)
* serviceImpl继承MPJBaseServiceImpl (可选)
### Lambda形式用法MPJLambdaWrapper
@ -73,7 +78,7 @@ class test {
void testJoin() {
//和Mybatis plus一致MPJLambdaWrapper的泛型必须是主表的泛型并且要用主表的Mapper来调用
MPJLambdaWrapper<UserDO> wrapper = JoinWrappers.lambda(UserDO.class)
MPJLambdaWrapper<UserDO> wrapper = JoinWrappers.lambda(User.class)
.selectAll(UserDO.class)//查询user表全部字段
.select(UserAddressDO::getTel)//查询user_address tel 字段
.selectAs(UserAddressDO::getAddress, UserDTO::getUserAddress)//别名
@ -110,8 +115,50 @@ WHERE (
AND t.id > ?)
```
# <a href="https://mybatis-plus-join.github.io" target="_blank">完整使用文档 wiki</a>
# 用爱发电
<a href="https://mybatis-plus-join.github.io/pages/quickstart/support.html" target="_blank">
<img alt="支持一下mybatis-plus-join" src="https://mybatis-plus-join.github.io/support.png">
</a>
说明:
* UserDTO.class 查询结果返回类(resultType)
* selectAll() 查询指定实体类的全部字段
* select() 查询指定的字段,支持可变参数,同一个select只能查询相同表的字段
* selectAs() 字段别名查询,用于数据库字段与业务实体类属性名不一致时使用
* leftJoin() 参数说明
第一个参数: 参与连表的实体类class
第二个参数: 连表的ON字段,这个属性必须是第一个参数实体类的属性
第三个参数: 参与连表的ON的另一个实体类属性
* 默认主表别名是t,其他的表别名以先后调用的顺序使用t1,t2,t3....
* 条件查询,可以查询主表以及参与连接的所有表的字段,全部调用mp原生的方法,正常使用没有sql注入风险
#### 一对多查询
```java
class test {
@Resource
private UserMapper userMapper;
@Test
void testResultMap() {
MPJLambdaWrapper<UserDO> wrapper = new MPJLambdaWrapper<>(User.class)
.selectAll(UserDO.class)
//对多查询
.selectCollection(AddressDO.class, UesrDTO::getAddressList)
//对一查询
.selectAssociation(AddressDO.class, UesrDTO::getAddress)
.leftJoin(AddressDO.class, AddressDO::getUserId, UserDO::getId);
List<UserDTO> dtoList = userMapper.selectJoinList(UserDTO.class, wrapper);
//关于对多分页查询
//由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。
}
}
```
MPJLambdaWrapper其他功能
* <a href="https://mybatisplusjoin.com/pages/core/lambda/select/selectCollection.html" target="_blank">
一对一,一对多使用</a>
* <a href="https://mybatisplusjoin.com/pages/core/lambda/select/selectFunc.html" target="_blank">简单的SQL函数使用</a>
* <a href="https://mybatisplusjoin.com/pages/core/lambda/join/leftJoin.html" target="_blank">ON语句多条件支持</a>
* <a href="https://www.baidu.com/link?url=wdmhssysW-Mj19Gkcc2CBOzNVoimHat57mlnH78SEU_6y0awYgDKTBy7es9BXnAH&wd=&eqid=908484020001866e000000056440b5e3" target="_blank">其他全部功能请参考使用文档</a>
# <a href="https://www.baidu.com/link?url=wdmhssysW-Mj19Gkcc2CBOzNVoimHat57mlnH78SEU_6y0awYgDKTBy7es9BXnAH&wd=&eqid=908484020001866e000000056440b5e3" target="_blank">使用文档 wiki</a>

View File

@ -1,46 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>mybatis-plus-join-adapter-jsqlparser-v46</artifactId>
<version>${revision}</version>
<name>mybatis-plus-join-adapter-jsqlparser-v46</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
<url>https://github.com/yulichang/mybatis-plus-join</url>
<licenses>
<license>
<name>The Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<developers>
<developer>
<id>mybatis-plus-join</id>
<name>yulichang</name>
<email>yu_lichang@qq.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</connection>
<developerConnection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</developerConnection>
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.5.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,63 +0,0 @@
package com.github.yulichang.adapter.jsqlparser.v46;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import java.util.function.Consumer;
/**
* 字段解析
*
* @author yulichang
* @since 1.4.12
*/
public class JSqlParserHelperV46 {
public static void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
try {
boolean parser = false;
Statement statement = CCJSqlParserUtil.parse(String.format("SELECT %s FROM table %s %s", selectSql, alias, from));
if (statement instanceof Select) {
Select select = (Select) statement;
SelectBody selectBody = select.getSelectBody();
if (selectBody instanceof PlainSelect) {
PlainSelect plainSelect = (PlainSelect) selectBody;
if (CollectionUtils.isNotEmpty(plainSelect.getSelectItems())) {
for (SelectItem item : plainSelect.getSelectItems()) {
if (item instanceof SelectExpressionItem) {
String col;
SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item;
if (null == selectExpressionItem.getAlias()) {
if (selectExpressionItem.getExpression() instanceof Column) {
col = ((Column) selectExpressionItem.getExpression()).getColumnName();
} else {
col = selectExpressionItem.getExpression().toString();
}
} else {
col = selectExpressionItem.getAlias().getName();
}
if (isNotBlank(col)) {
columConsumer.accept(col);
}
}
}
parser = true;
}
}
if (!parser)
throw ExceptionUtils.mpe("JSqlParser parser error <%s>", selectSql);
}
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
public static boolean isNotBlank(String str) {
return str != null && !str.trim().isEmpty();
}
}

View File

@ -1,53 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>mybatis-plus-join-adapter-jsqlparser</artifactId>
<version>${revision}</version>
<name>mybatis-plus-join-adapter-jsqlparser</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
<url>https://github.com/yulichang/mybatis-plus-join</url>
<licenses>
<license>
<name>The Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<developers>
<developer>
<id>mybatis-plus-join</id>
<name>yulichang</name>
<email>yu_lichang@qq.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</connection>
<developerConnection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</developerConnection>
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>${mybatis.plus.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>${mybatis.plus.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,57 +0,0 @@
package com.github.yulichang.adapter.jsqlparser;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.SelectItem;
import java.util.function.Consumer;
/**
* 字段解析
*
* @author yulichang
* @since 1.4.12
*/
public class JSqlParserHelper {
public static void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
try {
boolean parser = false;
Statement statement = CCJSqlParserUtil.parse(String.format("SELECT %s FROM table %s %s", selectSql, alias, from));
if (statement instanceof PlainSelect) {
PlainSelect plainSelect = (PlainSelect) statement;
if (CollectionUtils.isNotEmpty(plainSelect.getSelectItems())) {
for (SelectItem<?> item : plainSelect.getSelectItems()) {
String col;
if (item.getAlias() == null) {
if (item.getExpression() instanceof Column) {
Column column = (Column) item.getExpression();
col = column.getColumnName();
} else {
col = item.getExpression().toString();
}
} else {
col = item.getAlias().getName();
}
if (isNotBlank(col)) {
columConsumer.accept(col);
}
}
parser = true;
}
}
if (!parser)
throw ExceptionUtils.mpe("JSqlParser parser error <%s>", selectSql);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
public static boolean isNotBlank(String str) {
return str != null && !str.trim().isEmpty();
}
}

View File

@ -6,10 +6,10 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<artifactId>mybatis-plus-join-adapter-base</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
<name>mybatis-plus-join-adapter-base</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
@ -33,28 +33,21 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis.plus.version}</version>
<version>3.5.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>${mybatis.plus.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-jsqlparser</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-jsqlparser-v46</artifactId>
<version>${revision}</version>
</dependency>
</dependencies>
</project>

View File

@ -1,110 +0,0 @@
package com.github.yulichang.adapter.base;
import com.baomidou.mybatisplus.core.handlers.IJsonTypeHandler;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.MybatisUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.github.yulichang.adapter.base.metadata.OrderFieldInfo;
import com.github.yulichang.adapter.jsqlparser.JSqlParserHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.ibatis.type.UnknownTypeHandler;
import java.lang.reflect.Field;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.4.3
*/
public interface IAdapter {
default boolean mpjHasLogic(TableInfo tableInfo) {
return tableInfo.isWithLogicDelete();
}
default boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.isPrimitive();
}
default boolean isWithUpdateFill(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.isWithUpdateFill();
}
default String mpjMapping(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.getMapping();
}
default TableFieldInfo mpjGetLogicField(TableInfo tableInfo) {
return tableInfo.getLogicDeleteFieldInfo();
}
default boolean mpjHasPK(TableInfo tableInfo) {
return tableInfo.havePK();
}
default Configuration mpjGetConfiguration(TableInfo tableInfo) {
return tableInfo.getConfiguration();
}
default Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier) {
return fieldInfo.getField();
}
default List<OrderFieldInfo> mpjGetOrderField(TableInfo tableInfo) {
return tableInfo.getOrderByFields().stream().map(f ->
new OrderFieldInfo(f.getColumn(), f.getType(), f.getSort())).collect(Collectors.toList());
}
default void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
JSqlParserHelper.parserColum(alias, from, selectSql, columConsumer);
}
default TypeHandler<?> getTypeHandler(Configuration configuration, Class<?> propertyType, Class<? extends TypeHandler<?>> typeHandlerClass, Field field) {
TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(typeHandlerClass);
if (typeHandlerClass != null && typeHandlerClass != UnknownTypeHandler.class) {
if (IJsonTypeHandler.class.isAssignableFrom(typeHandlerClass)) {
// 保证每次实例化
typeHandler = MybatisUtils.newJsonTypeHandler(typeHandlerClass, propertyType, field);
} else {
if (typeHandler == null) {
typeHandler = registry.getInstance(propertyType, typeHandlerClass);
}
}
}
return typeHandler;
}
default void wrapperInnerPage(Interceptor interceptor, Predicate<Object> predicate, Function<Object, Object> function) {
if (interceptor instanceof MybatisPlusInterceptor) {
MybatisPlusInterceptor mybatisPlusInterceptor = (MybatisPlusInterceptor) interceptor;
try {
Field field = MybatisPlusInterceptor.class.getDeclaredField("interceptors");
field.setAccessible(true);
@SuppressWarnings("unchecked")
List<InnerInterceptor> interceptors = (List<InnerInterceptor>) field.get(mybatisPlusInterceptor);
interceptors.replaceAll(i -> {
if (i instanceof PaginationInnerInterceptor && !predicate.test(i)) {
return (InnerInterceptor) function.apply(i);
}
return i;
});
} catch (Exception e) {
throw ExceptionUtils.mpe(e);
}
}
}
}

View File

@ -0,0 +1,27 @@
package com.github.yulichang.adapter.base;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.session.Configuration;
import java.lang.reflect.Field;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.4.3
*/
public interface ITableInfoAdapter {
boolean mpjHasLogic(TableInfo tableInfo);
boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo);
TableFieldInfo mpjGetLogicField(TableInfo tableInfo);
boolean mpjHasPK(TableInfo tableInfo);
Configuration mpjGetConfiguration(TableInfo tableInfo);
Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier);
}

View File

@ -1,35 +0,0 @@
package com.github.yulichang.adapter.base.metadata;
import lombok.Data;
/**
* 兼容MP 3.5.4
* copy {@link com.baomidou.mybatisplus.core.metadata.OrderFieldInfo}
*
* @since 1.4.7
*/
@Data
public class OrderFieldInfo {
/**
* 字段
*/
private String column;
/**
* 排序类型
*/
private String type;
/**
* 排序顺序
*/
private short sort;
public OrderFieldInfo(String column, String type, short orderBySort) {
this.column = column;
this.type = type;
this.sort = orderBySort;
}
}

View File

@ -1,12 +0,0 @@
package com.github.yulichang.adapter.base.tookit;
public class CharSequenceUtils {
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
}

View File

@ -1,49 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
</parent>
<artifactId>mybatis-plus-join-adapter-v312</artifactId>
<version>${revision}</version>
<name>mybatis-plus-join-adapter-v312</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
<url>https://github.com/yulichang/mybatis-plus-join</url>
<licenses>
<license>
<name>The Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<developers>
<developer>
<id>mybatis-plus-join</id>
<name>yulichang</name>
<email>yu_lichang@qq.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</connection>
<developerConnection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</developerConnection>
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<dependencies>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-base</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,98 +0,0 @@
package com.github.yulichang.adapter.v312;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.base.IAdapter;
import com.github.yulichang.adapter.base.metadata.OrderFieldInfo;
import com.github.yulichang.adapter.base.tookit.CharSequenceUtils;
import com.github.yulichang.adapter.jsqlparser.v46.JSqlParserHelperV46;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.4.3
*/
public class Adapter312 implements IAdapter {
@Override
public boolean mpjHasLogic(TableInfo tableInfo) {
return tableInfo.isLogicDelete();
}
@Override
public boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.getPropertyType().isPrimitive();
}
@Override
public boolean isWithUpdateFill(TableFieldInfo tableFieldInfo) {
return false;
}
@Override
public String mpjMapping(TableFieldInfo tableFieldInfo) {
String el = tableFieldInfo.getEl();
if (el != null && el.contains(StringPool.COMMA)) {
return el.substring(el.indexOf(StringPool.COMMA) + 1);
}
return null;
}
@Override
public TableFieldInfo mpjGetLogicField(TableInfo tableInfo) {
return tableInfo.getFieldList().stream().filter(f -> Objects.nonNull(f.getLogicDeleteValue())
|| Objects.nonNull(f.getLogicNotDeleteValue())).findFirst().orElse(null);
}
@Override
public boolean mpjHasPK(TableInfo tableInfo) {
return CharSequenceUtils.isNotBlank(tableInfo.getKeyProperty()) ||
CharSequenceUtils.isNotBlank(tableInfo.getKeyColumn());
}
@Override
public Configuration mpjGetConfiguration(TableInfo tableInfo) {
return tableInfo.getConfiguration();
}
@Override
public Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier) {
return supplier.get();
}
@Override
public List<OrderFieldInfo> mpjGetOrderField(TableInfo tableInfo) {
throw new UnsupportedOperationException("不支持排序");
}
@Override
public void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
JSqlParserHelperV46.parserColum(alias, from, selectSql, columConsumer);
}
@Override
public TypeHandler<?> getTypeHandler(Configuration configuration, Class<?> propertyType, Class<? extends TypeHandler<?>> typeHandlerClass, Field field) {
TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(typeHandlerClass);
if (typeHandler == null) {
typeHandler = registry.getInstance(propertyType, typeHandlerClass);
}
return typeHandler;
}
@Override
public void wrapperInnerPage(Interceptor interceptor, Predicate<Object> predicate, Function<Object, Object> function) {
}
}

View File

@ -6,10 +6,10 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<artifactId>mybatis-plus-join-adapter-v33x</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
<name>mybatis-plus-join-adapter-v33x</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
@ -33,11 +33,20 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-base</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>

View File

@ -1,96 +0,0 @@
package com.github.yulichang.adapter.v33x;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.base.IAdapter;
import com.github.yulichang.adapter.base.metadata.OrderFieldInfo;
import com.github.yulichang.adapter.base.tookit.CharSequenceUtils;
import com.github.yulichang.adapter.base.tookit.VersionUtils;
import com.github.yulichang.adapter.jsqlparser.v46.JSqlParserHelperV46;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.4.3
*/
public class Adapter33x implements IAdapter {
private static final boolean is330 = VersionUtils.compare(VersionUtils.getVersion(), "3.3.0") == 0;
@Override
public boolean mpjHasLogic(TableInfo tableInfo) {
return tableInfo.isLogicDelete();
}
@Override
public boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.getPropertyType().isPrimitive();
}
@Override
public String mpjMapping(TableFieldInfo tableFieldInfo) {
String el = tableFieldInfo.getEl();
if (el != null && el.contains(StringPool.COMMA)) {
return el.substring(el.indexOf(StringPool.COMMA) + 1);
}
return null;
}
@Override
public TableFieldInfo mpjGetLogicField(TableInfo tableInfo) {
return tableInfo.getFieldList().stream().filter(f -> Objects.nonNull(f.getLogicDeleteValue())
|| Objects.nonNull(f.getLogicNotDeleteValue())).findFirst().orElse(null);
}
@Override
public boolean mpjHasPK(TableInfo tableInfo) {
return CharSequenceUtils.isNotBlank(tableInfo.getKeyProperty()) ||
CharSequenceUtils.isNotBlank(tableInfo.getKeyColumn());
}
@Override
public Configuration mpjGetConfiguration(TableInfo tableInfo) {
return tableInfo.getConfiguration();
}
@Override
public Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier) {
return is330 ? supplier.get() : IAdapter.super.mpjGetField(fieldInfo, null);
}
@Override
public List<OrderFieldInfo> mpjGetOrderField(TableInfo tableInfo) {
throw new UnsupportedOperationException("不支持排序");
}
@Override
public void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
JSqlParserHelperV46.parserColum(alias, from, selectSql, columConsumer);
}
@Override
public TypeHandler<?> getTypeHandler(Configuration configuration, Class<?> propertyType, Class<? extends TypeHandler<?>> typeHandlerClass, Field field) {
TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(typeHandlerClass);
if (typeHandler == null) {
typeHandler = registry.getInstance(propertyType, typeHandlerClass);
}
return typeHandler;
}
@Override
public void wrapperInnerPage(Interceptor interceptor, Predicate<Object> predicate, Function<Object, Object> function) {
}
}

View File

@ -0,0 +1,50 @@
package com.github.yulichang.adapter.v33x;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.yulichang.adapter.base.ITableInfoAdapter;
import org.apache.ibatis.session.Configuration;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.4.3
*/
public class TableInfoAdapterV33x implements ITableInfoAdapter {
@Override
public boolean mpjHasLogic(TableInfo tableInfo) {
return tableInfo.isLogicDelete();
}
@Override
public boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.getPropertyType().isPrimitive();
}
@Override
public TableFieldInfo mpjGetLogicField(TableInfo tableInfo) {
return tableInfo.getFieldList().stream().filter(f -> Objects.nonNull(f.getLogicDeleteValue())
|| Objects.nonNull(f.getLogicNotDeleteValue())).findFirst().orElse(null);
}
@Override
public boolean mpjHasPK(TableInfo tableInfo) {
return StringUtils.isNotBlank(tableInfo.getKeyProperty()) ||
StringUtils.isNotBlank(tableInfo.getKeyColumn());
}
@Override
public Configuration mpjGetConfiguration(TableInfo tableInfo) {
return tableInfo.getConfiguration();
}
@Override
public Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier) {
return supplier.get();
}
}

View File

@ -6,10 +6,10 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<artifactId>mybatis-plus-join-adapter-v3431</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
<name>mybatis-plus-join-adapter-v3431</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
@ -33,11 +33,20 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-base</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>

View File

@ -1,68 +0,0 @@
package com.github.yulichang.adapter.v3431;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.base.IAdapter;
import com.github.yulichang.adapter.base.metadata.OrderFieldInfo;
import com.github.yulichang.adapter.base.tookit.VersionUtils;
import com.github.yulichang.adapter.jsqlparser.v46.JSqlParserHelperV46;
import lombok.AllArgsConstructor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.Field;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.4.7
*/
@AllArgsConstructor
public class Adapter3431 implements IAdapter {
private static final boolean v = VersionUtils.compare(VersionUtils.getVersion(), "3.4.3") < 0;
@Override
public String mpjMapping(TableFieldInfo tableFieldInfo) {
if (v) {
String el = tableFieldInfo.getEl();
if (el != null && el.contains(StringPool.COMMA)) {
return el.substring(el.indexOf(StringPool.COMMA) + 1);
}
return null;
}
return IAdapter.super.mpjMapping(tableFieldInfo);
}
@Override
public List<OrderFieldInfo> mpjGetOrderField(TableInfo tableInfo) {
return v ? null : tableInfo.getOrderByFields().stream().map(f ->
new OrderFieldInfo(f.getColumn(), f.getOrderByType(), f.getOrderBySort())).collect(Collectors.toList());
}
@Override
public void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
JSqlParserHelperV46.parserColum(alias, from, selectSql, columConsumer);
}
@Override
public TypeHandler<?> getTypeHandler(Configuration configuration, Class<?> propertyType, Class<? extends TypeHandler<?>> typeHandlerClass, Field field) {
TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(typeHandlerClass);
if (typeHandler == null) {
typeHandler = registry.getInstance(propertyType, typeHandlerClass);
}
return typeHandler;
}
@Override
public void wrapperInnerPage(Interceptor interceptor, Predicate<Object> predicate, Function<Object, Object> function) {
}
}

View File

@ -6,10 +6,10 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<artifactId>mybatis-plus-join-adapter-v352</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
<name>mybatis-plus-join-adapter-v352</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
@ -33,6 +33,15 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>

View File

@ -1,39 +0,0 @@
package com.github.yulichang.adapter.v355;
import com.github.yulichang.adapter.base.IAdapter;
import com.github.yulichang.adapter.jsqlparser.v46.JSqlParserHelperV46;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import java.lang.reflect.Field;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* @author yulichang
* @since 1.4.12
*/
public class Adapter355 implements IAdapter {
@Override
public void parserColum(String alias, String from, String selectSql, Consumer<String> columConsumer) {
JSqlParserHelperV46.parserColum(alias, from, selectSql, columConsumer);
}
@Override
public TypeHandler<?> getTypeHandler(Configuration configuration, Class<?> propertyType, Class<? extends TypeHandler<?>> typeHandlerClass, Field field) {
TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(typeHandlerClass);
if (typeHandler == null) {
typeHandler = registry.getInstance(propertyType, typeHandlerClass);
}
return typeHandler;
}
@Override
public void wrapperInnerPage(Interceptor interceptor, Predicate<Object> predicate, Function<Object, Object> function) {
}
}

View File

@ -5,22 +5,18 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-root</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<packaging>pom</packaging>
<version>${revision}</version>
<version>1.4.5</version>
<artifactId>mybatis-plus-join-adapter</artifactId>
<name>mybatis-plus-join-adapter</name>
<modules>
<module>mybatis-plus-join-adapter-base</module>
<module>mybatis-plus-join-adapter-v312</module>
<module>mybatis-plus-join-adapter-v33x</module>
<module>mybatis-plus-join-adapter-v3431</module>
<module>mybatis-plus-join-adapter-v352</module>
<module>mybatis-plus-join-adapter-v355</module>
<module>jsqlparser/mybatis-plus-join-adapter-jsqlparser</module>
<module>jsqlparser/mybatis-plus-join-adapter-jsqlparser-v46</module>
</modules>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
@ -44,11 +40,12 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -7,9 +7,9 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-root</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<version>${revision}</version>
<version>1.4.5</version>
<artifactId>mybatis-plus-join-annotation</artifactId>
<name>mybatis-plus-join-annotation</name>
@ -33,4 +33,13 @@
<developerConnection>scm:git:https://github.com/yulichang/mybatis-plus-join.git</developerConnection>
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -4,13 +4,10 @@ import java.lang.annotation.*;
/**
* 动态表名注解
* <p>
* 1.5.2及以后无需添加此注解就可实现动态表名
*
* @author yulichang
* @since 1.4.4
*/
@Deprecated
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)

View File

@ -10,9 +10,9 @@ import java.lang.annotation.*;
* @since 1.2.0
*/
@Documented
@SuppressWarnings("unused")
@SuppressWarnings({"unused"})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface EntityMapping {
/**
@ -68,13 +68,13 @@ public @interface EntityMapping {
* 映射表查询条件之 orderBy<br/>
* 等效于 Wrappers.<T>query().orderByAsc(xxx);
*/
String[] orderByAsc() default "";
String orderByAsc() default "";
/**
* 映射表查询条件之 orderByDesc<br/>
* 等效于 Wrappers.<T>query().orderByDesc(xxx);
*/
String[] orderByDesc() default "";
String orderByDesc() default "";
/**
* 映射表查询条件之 last<br/>

View File

@ -10,9 +10,9 @@ import java.lang.annotation.*;
* @since 1.2.0
*/
@Documented
@SuppressWarnings("unused")
@SuppressWarnings({"unused"})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface FieldMapping {
/**
@ -66,13 +66,13 @@ public @interface FieldMapping {
* 映射表查询条件之 orderBy<br/>
* 等效于 Wrappers.<T>query().orderByAsc(xxx);
*/
String[] orderByAsc() default "";
String orderByAsc() default "";
/**
* 映射表查询条件之 orderByDesc<br/>
* 等效于 Wrappers.<T>query().orderByDesc(xxx);
*/
String[] orderByDesc() default "";
String orderByDesc() default "";
/**
* 映射表查询条件之 last<br/>

View File

@ -1,89 +0,0 @@
package com.github.yulichang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* apt注解
* <p>
* 默认为String.format
* <p>
* 举例
* <ul>
* <li>全大写 %S</li>
* <li>加APT后缀 %sAPT</li>
* <li>加APT前缀 APT%s</li>
* <li>加APT后缀并且大写 %SAPT</li>
* </ul>
* <p>
* 支持Ognl语法,字段说明<br/>
* Ognl上下文
* <ul>
* <li>className 类名</li>
* <li>classPackage 包名</li>
* <li>
* util 工具类 OgnlUtil {@link com.github.yulichang.processor.utils.OgnlUtil} ,
* <a href="https://github.com/yulichang/mybatis-plus-join/tree/master/plugin/mybatis-plus-join-processor/src/main/java/com/github/yulichang/processor/utils/OgnlUtil.java">
* github link
* </a>
* </li>
* </ul>
* 指定开头 Ognl# 这不是ognl语法这是MPJ规定的 用于区分 ognl还是String.format
* <p>
* 举例
* <ul>
* <li>去掉3长度的后缀并且大写 Ognl#className.substring(0, className.length() - 3).toUpperCase() </li>
* <li>APT结尾 Ognl#className + 'APT'</li>
* <li>全大写并且以APT结尾 Ognl#className.toUpperCase() + 'APT' </li>
* <li>"PO"结尾替换为APT且全大写 Ognl#util.replaceSuffix(className, 'PO', 'APT').toUpperCase() </li>
* </ul>
* <p>
* 支持 三元运算 String所有方法 如lastIndexOf subString toUpperCase等 Ognl语法<p>
*
* @author yulichang
* @since 1.5.0
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Table {
/**
* APT类名
* <p>
* 支持Ognl 默认使用String.format()
*/
String value() default "%sCol";
/**
* 生成类的包名
* <p>
* 支持Ognl 默认使用String.format()
*/
String classPackage() default "%s.apt";
/**
* 是否在Tables中生成对应的类字段
*/
boolean genTables() default true;
/**
* Tables中的字段名 默认大写的类名
* <p>
* 支持Ognl 默认使用String.format()
*/
String tablesClassPackage() default "%s.tables";
/**
* Tables中的字段名 默认大写的类名
* <p>
* 支持Ognl 默认使用String.format()
*/
String tablesClassName() default "%S";
/**
* 是否缓存
*/
boolean cache() default true;
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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">
@ -6,9 +7,9 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-root</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<version>${revision}</version>
<version>1.4.5</version>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<name>mybatis-plus-join-boot-starter</name>
@ -33,26 +34,37 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-extension</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>${mybatis.plus.version}</version>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -1,27 +1,21 @@
package com.github.yulichang.autoconfigure;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.github.yulichang.autoconfigure.conditional.JoinSqlInjectorCondition;
import com.github.yulichang.autoconfigure.consumer.MybatisPlusJoinIfExistsConsumer;
import com.github.yulichang.autoconfigure.consumer.MybatisPlusJoinPropertiesConsumer;
import com.github.yulichang.autoconfigure.conditional.MPJSqlInjectorCondition;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.config.MPJInterceptorConfig;
import com.github.yulichang.config.enums.LogicDelTypeEnum;
import com.github.yulichang.extension.mapping.config.MappingConfig;
import com.github.yulichang.toolkit.SpringContentUtils;
import com.github.yulichang.injector.MPJSqlInjector;
import com.github.yulichang.interceptor.MPJInterceptor;
import com.github.yulichang.toolkit.SpringContentUtils;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import com.github.yulichang.wrapper.interfaces.MBiPredicate;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -41,7 +35,6 @@ import org.springframework.core.annotation.Order;
import javax.sql.DataSource;
import java.util.List;
import java.util.Optional;
/**
* springboot 自动配置类
@ -49,34 +42,30 @@ import java.util.Optional;
* @author yulichang
* @since 1.3.7
*/
@SuppressWarnings("ALL")
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisPlusJoinProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusJoinAutoConfiguration {
private static final Logger logger = LoggerFactory.getLogger(MybatisPlusJoinAutoConfiguration.class);
@SuppressWarnings("FieldCanBeLocal")
private final MybatisPlusJoinProperties properties;
public MybatisPlusJoinAutoConfiguration(MybatisPlusJoinProperties properties,
ObjectProvider<MybatisPlusJoinPropertiesConsumer> propertiesConsumers,
ObjectProvider<MybatisPlusJoinIfExistsConsumer> IfExistsConsumers) {
this.properties = Optional.ofNullable(propertiesConsumers.getIfAvailable()).map(c -> c.config(properties)).orElse(properties);
ConfigProperties.banner = this.properties.getBanner();
ConfigProperties.msCache = this.properties.isMsCache();
ConfigProperties.tableAlias = this.properties.getTableAlias();
ConfigProperties.joinPrefix = this.properties.getJoinPrefix();
ConfigProperties.logicDelType = this.properties.getLogicDelType();
ConfigProperties.subQueryAlias = this.properties.getSubQueryAlias();
ConfigProperties.subTableLogic = this.properties.getSubTableLogic();
ConfigProperties.mappingMaxCount = this.properties.getMappingMaxCount();
ConfigProperties.Convert.IfExists = this.properties.getIfExists();
ConfigProperties.ifExists = Optional.ofNullable(IfExistsConsumers.getIfAvailable())
.map(m -> (MBiPredicate<Object, IfExistsSqlKeyWordEnum>) m)
.orElse((val, key) -> ConfigProperties.Convert.IfExists.test(val));
info("mybatis plus join properties config complete");
public MybatisPlusJoinAutoConfiguration(MybatisPlusJoinProperties properties) {
this.properties = properties;
ConfigProperties.subTableLogic = properties.getSubTableLogic();
ConfigProperties.msCache = properties.isMsCache();
ConfigProperties.tableAlias = properties.getTableAlias();
ConfigProperties.joinPrefix = properties.getJoinPrefix();
ConfigProperties.logicDelType = "where".equalsIgnoreCase(properties.getLogicDelType()) ?
LogicDelTypeEnum.WHERE : LogicDelTypeEnum.ON;
ConfigProperties.mappingMaxCount = properties.getMappingMaxCount();
}
/**
@ -92,9 +81,8 @@ public class MybatisPlusJoinAutoConfiguration {
* mybatis plus 拦截器配置
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public MPJInterceptorConfig mpjInterceptorConfig(List<SqlSessionFactory> sqlSessionFactoryList) {
public MPJInterceptorConfig mpjInterceptorConfig(@Autowired(required = false) List<SqlSessionFactory> sqlSessionFactoryList) {
return new MPJInterceptorConfig(sqlSessionFactoryList, properties.getBanner());
}
@ -103,12 +91,12 @@ public class MybatisPlusJoinAutoConfiguration {
*/
@Bean
@Primary
@JoinSqlInjectorCondition
@MPJSqlInjectorCondition
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnBean(ISqlInjector.class)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public MPJSqlInjector mpjSqlInjector(ISqlInjector sqlInjector) {
info("mybatis plus join SqlInjector init");
logger.info("MPJSqlInjector init");
return new MPJSqlInjector(sqlInjector);
}
@ -120,72 +108,45 @@ public class MybatisPlusJoinAutoConfiguration {
@ConditionalOnMissingBean(ISqlInjector.class)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public MPJSqlInjector mpjSqlInjectorOnMiss() {
info("mybatis plus join SqlInjector init");
logger.info("MPJSqlInjector init");
return new MPJSqlInjector();
}
/**
* springboot context 工具类
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public SpringContentUtils mpjSpringContent(@Autowired(required = false) MPJSpringContext springContext) {
return new SpringContentUtils(springContext);
}
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public static class MPJMappingConfig implements ApplicationListener<ApplicationReadyEvent> {
@Override
@SuppressWarnings("NullableProblems")
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
MappingConfig.init();
}
}
private static void info(String info) {
if (ConfigProperties.banner) {
logger.info(info);
new MappingConfig();
}
}
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
public static class MPJSpringContext implements SpringContentUtils.SpringContext, BeanFactoryPostProcessor, ApplicationContextAware {
public static class MPJSpringContext implements SpringContentUtils.SpringContext, ApplicationContextAware {
private ApplicationContext applicationContext;
private ListableBeanFactory listableBeanFactory;
@Override
public <T> T getBean(Class<T> clazz) {
return getBeanFactory().getBean(clazz);
return this.applicationContext.getBean(clazz);
}
@Override
public <T> void getBeansOfType(Class<T> clazz) {
getBeanFactory().getBeansOfType(clazz);
}
private ListableBeanFactory getBeanFactory() {
return applicationContext == null ? listableBeanFactory : applicationContext;
}
@Override
@SuppressWarnings("NullableProblems")
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
SpringContentUtils.setSpringContext(this);
}
@Override
@SuppressWarnings("NullableProblems")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
this.listableBeanFactory = beanFactory;
SpringContentUtils.setSpringContext(this);
try {
String[] names = beanFactory.getBeanNamesForType(SqlSessionFactory.class);
for (String name : names) {
BeanDefinition definition = beanFactory.getBeanDefinition(name);
info(String.format("MPJ SqlSessionFactory bean definition: %s factoryBeanName: %s factoryMethodName: %s source: %s",
name, definition.getFactoryBeanName(), definition.getFactoryMethodName(), definition.getSource()));
}
} catch (Exception ignore) {
}
}
}
}

View File

@ -1,7 +1,5 @@
package com.github.yulichang.autoconfigure;
import com.github.yulichang.config.enums.IfExistsEnum;
import com.github.yulichang.config.enums.LogicDelTypeEnum;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ -45,7 +43,7 @@ public class MybatisPlusJoinProperties {
/**
* 逻辑删除类型 支持 where on
*/
private LogicDelTypeEnum logicDelType = LogicDelTypeEnum.ON;
private String logicDelType = "where";
/**
* 映射查询最大深度
@ -56,15 +54,4 @@ public class MybatisPlusJoinProperties {
* 子查询别名
*/
private String subQueryAlias = "st";
/**
* Wrapper IfExists 判断策略
* <p>
* NOT_NULL 非null
* <p>
* NOT_EMPTY 非空字符串 "" -> false, " " -> true ...
* <p>
* NOT_BLANK 非空白字符串 "" -> false, " " -> false, "\r" -> false, "abc" -> true ...
*/
private IfExistsEnum IfExists = IfExistsEnum.NOT_EMPTY;
}

View File

@ -13,5 +13,5 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Conditional(OnSqlInjectorCondition.class)
public @interface JoinSqlInjectorCondition {
public @interface MPJSqlInjectorCondition {
}

View File

@ -1,13 +0,0 @@
package com.github.yulichang.autoconfigure.consumer;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import com.github.yulichang.wrapper.interfaces.MBiPredicate;
/**
* 自定义IfExists策略
*
* @author yulichang
* @since 1.4.9
*/
public interface MybatisPlusJoinIfExistsConsumer extends MBiPredicate<Object, IfExistsSqlKeyWordEnum> {
}

View File

@ -1,20 +0,0 @@
package com.github.yulichang.autoconfigure.consumer;
import com.github.yulichang.autoconfigure.MybatisPlusJoinProperties;
/**
* 自定义配置
*
* @author yulichang
* @since 1.4.9
*/
public interface MybatisPlusJoinPropertiesConsumer {
/**
* 自定义配置此方法会覆盖配置文件中的MPJ配置
*
* @param properties 配置文件里的配置
* @return 修改后的配置
*/
MybatisPlusJoinProperties config(MybatisPlusJoinProperties properties);
}

View File

@ -40,8 +40,8 @@
},
{
"name": "mybatis-plus-join.logic-del-type",
"defaultValue": "com.github.yulichang.config.enums.LogicDelTypeEnum.ON",
"type": "com.github.yulichang.config.enums.LogicDelTypeEnum",
"defaultValue": "where",
"type": "java.lang.String",
"description": "逻辑删除的位置支持where和on两个."
},
{
@ -55,12 +55,21 @@
"defaultValue": "st",
"type": "java.lang.String",
"description": "子查询表别名."
},
}
],
"hints": [
{
"name": "mybatis-plus-join.if-exist",
"defaultValue": "com.github.yulichang.config.enums.IfExistsEnum.NOT_EMPTY",
"type": "com.github.yulichang.config.enums.IfExistsEnum",
"description": "IfExists方法判断策略,如需自定义请用@Bean形式MybatisPlusJoinIfExistsConsumer."
"name": "mybatis-plus-join.logic-del-type",
"values": [
{
"value": "where",
"description": "logic delete condition to where."
},
{
"value": "on",
"description": "logic delete condition to on."
}
]
}
]
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress VulnerableLibrariesLocal -->
<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">
@ -6,9 +7,9 @@
<parent>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-root</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</parent>
<version>${revision}</version>
<version>1.4.5</version>
<artifactId>mybatis-plus-join-core</artifactId>
<name>mybatis-plus-join-core</name>
@ -33,90 +34,53 @@
<url>https://github.com/yulichang/mybatis-plus-join</url>
</scm>
<properties>
<jdkVersion>1.8</jdkVersion>
<jdkVersion.test>1.8</jdkVersion.test>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<github.global.server>github</github.global.server>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-annotation</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-v312</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-v33x</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-v3431</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-v352</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-adapter-v355</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-wrapper-ext</artifactId>
<version>${revision}</version>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis.plus.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>${mybatis.plus.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring</artifactId>
<version>${mybatis.plus.version}</version>
<version>3.5.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>5.3.23</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,11 +0,0 @@
package com.github.yulichang.adapter;
import com.github.yulichang.adapter.base.IAdapter;
/**
* @author yulichang
* @since 1.4.3
*/
public class Adapter implements IAdapter {
}

View File

@ -1,13 +1,8 @@
package com.github.yulichang.adapter;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.github.yulichang.adapter.base.IAdapter;
import com.github.yulichang.adapter.base.tookit.VersionUtils;
import com.github.yulichang.adapter.v312.Adapter312;
import com.github.yulichang.adapter.v33x.Adapter33x;
import com.github.yulichang.adapter.v3431.Adapter3431;
import com.github.yulichang.adapter.v355.Adapter355;
import lombok.Getter;
import com.baomidou.mybatisplus.core.MybatisPlusVersion;
import com.github.yulichang.adapter.base.ITableInfoAdapter;
import com.github.yulichang.adapter.v33x.TableInfoAdapterV33x;
/**
* @author yulichang
@ -15,28 +10,11 @@ import lombok.Getter;
*/
public class AdapterHelper {
@Getter
private static IAdapter adapter;
static {
String version = VersionUtils.getVersion();
if (VersionUtils.compare(version, "3.5.6") >= 0) {
adapter = new Adapter();
} else if (VersionUtils.compare(version, "3.5.4") >= 0) {
adapter = new Adapter355();
} else if (VersionUtils.compare(version, "3.4.0") >= 0) {
adapter = new Adapter3431();
} else if (VersionUtils.compare(version, "3.3.0") >= 0) {
adapter = new Adapter33x();
} else if (VersionUtils.compare(version, "3.1.2") >= 0) {
adapter = new Adapter312();
} else {
throw ExceptionUtils.mpe("MPJ需要MP版本3.1.2+当前MP版本%s", version);
public static ITableInfoAdapter getTableInfoAdapter() {
String version = MybatisPlusVersion.getVersion();
if (version.startsWith("3.3.")) {
return new TableInfoAdapterV33x();
}
}
public static void setAdapter(IAdapter adapter) {
AdapterHelper.adapter = adapter;
return new TableInfoAdapter();
}
}

View File

@ -0,0 +1,46 @@
package com.github.yulichang.adapter;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.github.yulichang.adapter.base.ITableInfoAdapter;
import org.apache.ibatis.session.Configuration;
import java.lang.reflect.Field;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.4.3
*/
public class TableInfoAdapter implements ITableInfoAdapter {
@Override
public boolean mpjHasLogic(TableInfo tableInfo) {
return tableInfo.isWithLogicDelete();
}
@Override
public boolean mpjIsPrimitive(TableFieldInfo tableFieldInfo) {
return tableFieldInfo.isPrimitive();
}
@Override
public TableFieldInfo mpjGetLogicField(TableInfo tableInfo) {
return tableInfo.getLogicDeleteFieldInfo();
}
@Override
public boolean mpjHasPK(TableInfo tableInfo) {
return tableInfo.havePK();
}
@Override
public Configuration mpjGetConfiguration(TableInfo tableInfo) {
return tableInfo.getConfiguration();
}
@Override
public Field mpjGetField(TableFieldInfo fieldInfo, Supplier<Field> supplier) {
return fieldInfo.getField();
}
}

View File

@ -1,137 +0,0 @@
package com.github.yulichang.base;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.toolkit.Constant;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* join相关方法
*
* @author yulichang
*/
public interface JoinMapper<T> {
/**
* 根据 Wrapper 条件连表删除
*
* @param wrapper joinWrapper
*/
int deleteJoin(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 whereEntity 条件更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
int updateJoin(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 whereEntity 条件更新记录 (null字段也会更新 !!!)
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
int updateJoinAndNull(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 Wrapper 条件查询总记录数
*
* @param wrapper joinWrapper
*/
Long selectJoinCount(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回一条记录
*
* @param wrapper joinWrapper
* @return T
*/
default T selectJoinOne(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
return selectJoinOne(null, wrapper);
}
/**
* 连表查询返回一条记录
*
* @param wrapper joinWrapper
* @param clazz resultType
*/
<DTO> DTO selectJoinOne(@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map
*
* @param wrapper joinWrapper
*/
default Map<String, Object> selectJoinMap(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
//noinspection unchecked
return selectJoinOne(Map.class, wrapper);
}
/**
* 连表查询返回记录集合
*
* @param wrapper joinWrapper
* @return List&lt;T&gt;
*/
default List<T> selectJoinList(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
return selectJoinList(null, wrapper);
}
/**
* 连表查询返回记录集合
*
* @param wrapper joinWrapper
* @param clazz resultType
*/
<DTO> List<DTO> selectJoinList(@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map集合
*
* @param wrapper joinWrapper
*/
default List<Map<String, Object>> selectJoinMaps(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
//noinspection unchecked
return (List<Map<String, Object>>) ((Object) selectJoinList(Map.class, wrapper));
}
/**
* 连表查询返回记录集合并分页
*
* @param wrapper joinWrapper
*/
default <P extends IPage<T>> P selectJoinPage(P page, @Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
return selectJoinPage(page, null, wrapper);
}
/**
* 连表查询返回记录集合并分页
*
* @param wrapper joinWrapper
* @param clazz resultType
* @param <DTO> 分页返回对象
*/
<DTO, P extends IPage<DTO>> P selectJoinPage(P page,
@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map集合并分页
*
* @param wrapper joinWrapper
*/
default <P extends IPage<Map<String, Object>>> P selectJoinMapsPage(P page,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper) {
//noinspection unchecked,rawtypes
return (P) selectJoinPage((IPage) page, Map.class, wrapper);
}
}

View File

@ -1,93 +0,0 @@
package com.github.yulichang.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.interfaces.MPJBaseJoin;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"unchecked", "unused"})
public interface JoinService<T> {
BaseMapper<T> getBaseMapper();
/**
* 根据 Wrapper 条件连表删除
*
* @param wrapper joinWrapper
*/
default boolean deleteJoin(MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((JoinMapper<T>) getBaseMapper()).deleteJoin(wrapper));
}
/**
* 根据 whereEntity 条件更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
default boolean updateJoin(T entity, MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((JoinMapper<T>) getBaseMapper()).updateJoin(entity, wrapper));
}
/**
* 根据 whereEntity 条件更新记录 (null字段也会更新 !!!)
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
default boolean updateJoinAndNull(T entity, MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((JoinMapper<T>) getBaseMapper()).updateJoinAndNull(entity, wrapper));
}
/**
* 根据 Wrapper 条件查询总记录数
*/
default Long selectJoinCount(MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinCount(wrapper);
}
/**
* 连接查询返回一条记录
*/
default <DTO> DTO selectJoinOne(Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinOne(clazz, wrapper);
}
/**
* 连接查询返回集合
*/
default <DTO> List<DTO> selectJoinList(Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinList(clazz, wrapper);
}
/**
* 连接查询返回集合并分页
*/
default <DTO, P extends IPage<DTO>> P selectJoinListPage(P page, Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinPage(page, clazz, wrapper);
}
/**
* 连接查询返回Map
*/
default Map<String, Object> selectJoinMap(MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinMap(wrapper);
}
/**
* 连接查询返回Map集合
*/
default List<Map<String, Object>> selectJoinMaps(MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinMaps(wrapper);
}
/**
* 连接查询返回Map集合并分页
*/
default <P extends IPage<Map<String, Object>>> P selectJoinMapsPage(P page, MPJBaseJoin<T> wrapper) {
return ((JoinMapper<T>) getBaseMapper()).selectJoinMapsPage(page, wrapper);
}
}

View File

@ -1,11 +1,99 @@
package com.github.yulichang.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.toolkit.Constant;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @author yulichang
* @see BaseMapper
*/
public interface MPJBaseMapper<T> extends BaseMapper<T>, JoinMapper<T> {
public interface MPJBaseMapper<T> extends BaseMapper<T> {
/**
* 根据 Wrapper 条件连表删除
*
* @param wrapper joinWrapper
*/
int deleteJoin(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 whereEntity 条件更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
int updateJoin(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 whereEntity 条件更新记录 (null字段也会更新 !!!)
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
int updateJoinAndNull(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 根据 Wrapper 条件查询总记录数
*
* @param wrapper joinWrapper
*/
Long selectJoinCount(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回一条记录
*
* @param wrapper joinWrapper
* @param clazz resultType
*/
<DTO> DTO selectJoinOne(@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map
*
* @param wrapper joinWrapper
*/
Map<String, Object> selectJoinMap(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回记录集合
*
* @param wrapper joinWrapper
* @param clazz resultType
*/
<DTO> List<DTO> selectJoinList(@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map集合
*
* @param wrapper joinWrapper
*/
List<Map<String, Object>> selectJoinMaps(@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回记录集合并分页
*
* @param wrapper joinWrapper
* @param clazz resultType
* @param <DTO> 分页返回对象
*/
<DTO, P extends IPage<DTO>> P selectJoinPage(P page,
@Param(Constant.CLAZZ) Class<DTO> clazz,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
/**
* 连表查询返回Map集合并分页
*
* @param wrapper joinWrapper
*/
<P extends IPage<Map<String, Object>>> P selectJoinMapsPage(P page,
@Param(Constants.WRAPPER) MPJBaseJoin<T> wrapper);
}

View File

@ -1,6 +1,12 @@
package com.github.yulichang.base;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.interfaces.MPJBaseJoin;
import java.util.List;
import java.util.Map;
/**
* 基础service
@ -9,6 +15,84 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @author yulichang
*/
@SuppressWarnings({"unused"})
public interface MPJBaseService<T> extends IService<T>, JoinService<T> {
public interface MPJBaseService<T> extends IService<T> {
/**
* 根据 Wrapper 条件连表删除
*
* @param wrapper joinWrapper
*/
default boolean deleteJoin(MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((MPJBaseMapper<T>) getBaseMapper()).deleteJoin(wrapper));
}
/**
* 根据 whereEntity 条件更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
default boolean updateJoin(T entity, MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((MPJBaseMapper<T>) getBaseMapper()).updateJoin(entity, wrapper));
}
/**
* 根据 whereEntity 条件更新记录 (null字段也会更新 !!!)
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param wrapper 实体对象封装操作类可以为 null,里面的 entity 用于生成 where 语句
*/
default boolean updateJoinAndNull(T entity, MPJBaseJoin<T> wrapper) {
return SqlHelper.retBool(((MPJBaseMapper<T>) getBaseMapper()).updateJoinAndNull(entity, wrapper));
}
/**
* 根据 Wrapper 条件查询总记录数
*/
default Long selectJoinCount(MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinCount(wrapper);
}
/**
* 连接查询返回一条记录
*/
default <DTO> DTO selectJoinOne(Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinOne(clazz, wrapper);
}
/**
* 连接查询返回集合
*/
default <DTO> List<DTO> selectJoinList(Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinList(clazz, wrapper);
}
/**
* 连接查询返回集合并分页
*/
default <DTO, P extends IPage<DTO>> P selectJoinListPage(P page, Class<DTO> clazz, MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinPage(page, clazz, wrapper);
}
/**
* 连接查询返回Map
*/
default Map<String, Object> selectJoinMap(MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinMap(wrapper);
}
/**
* 连接查询返回Map集合
*/
default List<Map<String, Object>> selectJoinMaps(MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinMaps(wrapper);
}
/**
* 连接查询返回Map集合并分页
*/
default <P extends IPage<Map<String, Object>>> P selectJoinMapsPage(P page, MPJBaseJoin<T> wrapper) {
return ((MPJBaseMapper<T>) getBaseMapper()).selectJoinMapsPage(page, wrapper);
}
}

View File

@ -1,9 +1,8 @@
package com.github.yulichang.config;
import com.github.yulichang.config.enums.IfExistsEnum;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.adapter.base.ITableInfoAdapter;
import com.github.yulichang.config.enums.LogicDelTypeEnum;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import com.github.yulichang.wrapper.interfaces.MBiPredicate;
/**
* @author yulichang
@ -11,10 +10,6 @@ import com.github.yulichang.wrapper.interfaces.MBiPredicate;
*/
public class ConfigProperties {
/**
* 是否打印banner
*/
public static boolean banner = true;
/**
* 是否开启副表逻辑删除
*/
@ -34,31 +29,17 @@ public class ConfigProperties {
/**
* 逻辑删除类型 支持 where on
*/
public static LogicDelTypeEnum logicDelType = LogicDelTypeEnum.ON;
public static LogicDelTypeEnum logicDelType = LogicDelTypeEnum.WHERE;
/**
* 映射查询最大深度
* 逻辑删除类型 支持 where on
*/
public static int mappingMaxCount = 5;
/**
* TableInfo适配器
*/
public static ITableInfoAdapter tableInfoAdapter = AdapterHelper.getTableInfoAdapter();
/**
* 子查询别名
*/
public static String subQueryAlias = "st";
/**
* Wrapper IfExists 判断策略
* <p>
* NOT_NULL 非null
* <p>
* NOT_EMPTY 非空字符串 "" -> false, " " -> true ...
* <p>
* NOT_BLANK 非空白字符串 "" -> false, " " -> false, "\r" -> false, "abc" -> true ...
*/
public static MBiPredicate<Object, IfExistsSqlKeyWordEnum> ifExists = (val, key) -> IfExistsEnum.NOT_EMPTY.test(val);
/**
* 暂存 不可使用 用于规避starter包中需要序列化
*/
public static class Convert {
public static IfExistsEnum IfExists = IfExistsEnum.NOT_EMPTY;
}
}

View File

@ -3,7 +3,6 @@ package com.github.yulichang.config;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.yulichang.interceptor.MPJInterceptor;
import com.github.yulichang.toolkit.InterceptorList;
import com.github.yulichang.toolkit.MybatisJoinPlusVersion;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.plugin.Interceptor;
@ -31,10 +30,11 @@ public class MPJInterceptorConfig {
System.out.println(" _ _ |_ _ _|_. ___ _ | _ . _ . _ \n" +
"| | |\\/|_)(_| | |_\\ |_)||_|_\\ | (_) | | | \n" +
" / | /\n" +
" " + MybatisJoinPlusVersion.getVersion());
" 1.4.5");
}
}
@SuppressWarnings("unchecked")
private void replaceInterceptorChain(List<SqlSessionFactory> sqlSessionFactoryList) {
if (CollectionUtils.isEmpty(sqlSessionFactoryList)) {
return;
@ -46,7 +46,6 @@ public class MPJInterceptorConfig {
InterceptorChain chain = (InterceptorChain) interceptorChain.get(factory.getConfiguration());
Field interceptors = InterceptorChain.class.getDeclaredField("interceptors");
interceptors.setAccessible(true);
@SuppressWarnings("unchecked")
List<Interceptor> list = (List<Interceptor>) interceptors.get(chain);
if (CollectionUtils.isEmpty(list)) {
interceptors.set(chain, new InterceptorList<>());
@ -55,7 +54,8 @@ public class MPJInterceptorConfig {
}
chain.addInterceptor(new MPJInterceptor());
} catch (NoSuchFieldException | IllegalAccessException e) {
logger.error("初始化 MPJ 拦截器失败", e);
logger.error("初始化 MPJ 拦截器失败");
e.printStackTrace();
}
}
}

View File

@ -1,40 +0,0 @@
package com.github.yulichang.config.enums;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.wrapper.interfaces.MPredicate;
import java.io.Serializable;
import java.util.Objects;
/**
* 条件判断策略
*
* @author yulichang
* @since 1.4.9
*/
public enum IfExistsEnum implements MPredicate<Object>, Serializable {
/**
* 非null
*/
NOT_NULL(Objects::nonNull),
/**
* 非空字符串 "" -> false, " " -> true ...
*/
NOT_EMPTY(val -> NOT_NULL.and(v -> !(v instanceof CharSequence) || StrUtils.isNotEmpty((CharSequence) v)).test(val)),
/**
* NOT_BLANK 非空白字符串 "" -> false, " " -> false, "\r" -> false, "abc" -> true ...
*/
NOT_BLANK(val -> NOT_NULL.and(v -> !(v instanceof CharSequence) || StrUtils.isNotBlank((CharSequence) v)).test(val));
private final MPredicate<Object> predicate;
IfExistsEnum(MPredicate<Object> predicate) {
this.predicate = predicate;
}
@Override
public boolean test(Object obj) {
return this.predicate.test(obj);
}
}

View File

@ -1,13 +1,11 @@
package com.github.yulichang.config.enums;
import java.io.Serializable;
/**
* 逻辑删除位置
*
* @author yulichang
* @since 1.4.4
*/
public enum LogicDelTypeEnum implements Serializable {
public enum LogicDelTypeEnum {
WHERE, ON
}

View File

@ -1,451 +0,0 @@
package com.github.yulichang.extension.apt;
import com.baomidou.mybatisplus.annotation.OrderBy;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.config.enums.LogicDelTypeEnum;
import com.github.yulichang.extension.apt.interfaces.QueryJoin;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.toolkit.*;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.segments.PageInfo;
import com.github.yulichang.wrapper.segments.SelectCache;
import lombok.Getter;
import lombok.Setter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.baomidou.mybatisplus.core.enums.WrapperKeyword.APPLY;
import static java.util.stream.Collectors.joining;
/**
* 参考 {@link com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper}
*
* @author yulichang
*/
@SuppressWarnings({"DuplicatedCode", "unused"})
public abstract class AptAbstractWrapper<T, Children extends AptAbstractWrapper<T, Children>>
extends JoinAbstractWrapper<T, Children> implements QueryJoin<Children, T> {
/**
* 主表别名
*/
@Getter
protected String alias = ConfigProperties.tableAlias;
/**
* 副表别名
*/
protected String subTableAlias = ConfigProperties.tableAlias;
/**
* 是否构建是否存在一对多
*/
@Getter
protected boolean resultMap = false;
@Getter
protected boolean resultMapCollection = false;
@Setter
protected PageInfo pageInfo;
@Getter
protected boolean pageByMain = false;
/**
* 表序号
*/
protected int tableIndex = 1;
protected boolean isMain = true;
/**
* 主表 表名处理方法
*/
protected boolean dynamicTableName = false;
/**
* 主表 表名处理方法
*/
protected SFunction<String, String> tableFunc;
/**
* 逻辑删除位置
*/
protected LogicDelTypeEnum logicDelType = ConfigProperties.logicDelType;
/**
* 查询表
*/
protected final SharedString from = new SharedString();
/**
* 是否有表别名
*/
@Getter
protected boolean hasAlias;
/**
* 连表关键字 on 条件 func 使用
*/
@Getter
protected String keyWord;
/**
* 副表逻辑删除开关
*/
protected boolean subLogicSql = ConfigProperties.subTableLogic;
/**
* 主表逻辑删除开关
*/
protected boolean logicSql = true;
@Getter
protected BaseColumn<T> baseColumn;
/**
* apt别名对应
*/
@Getter
protected TableMap aptIndex;
/**
* 构造方法
*/
protected AptAbstractWrapper(BaseColumn<T> baseColumn) {
this.alias = StrUtils.isNotBlank(baseColumn.getAlias()) ? baseColumn.getAlias() : this.alias;
setEntityClass(baseColumn.getColumnClass());
this.baseColumn = baseColumn;
initNeed();
}
/**
* 构造方法
*
* @param entity 主表实体类
*/
protected AptAbstractWrapper(BaseColumn<T> baseColumn, T entity) {
this.alias = StrUtils.isNotBlank(baseColumn.getAlias()) ? baseColumn.getAlias() : this.alias;
setEntity(entity);
this.baseColumn = baseColumn;
initNeed();
}
/**
* 根据主表分页
*/
public Children pageByMain() {
this.pageByMain = true;
return typedThis;
}
/**
* 根据主表分页
*/
public Children pageByMain(MFunction<PageInfo> function) {
this.pageByMain = true;
function.apply(getPageInfo());
return typedThis;
}
public PageInfo getPageInfo() {
if (pageInfo == null) {
pageInfo = new PageInfo();
}
return pageInfo;
}
/**
* 设置表别名
* 设置表别名注意sql注入问题
*
* @return 自定义表别名
*/
public Children setTableName(SFunction<String, String> tableFunc) {
if (isMain) {
if (tableFunc != null) {
this.dynamicTableName = true;
this.tableFunc = tableFunc;
}
} else {
this.tableName = tableFunc.apply(this.tableName);
}
return typedThis;
}
public String getTableName(String tableName) {
if (isMain) {
if (dynamicTableName) {
return tableFunc.apply(tableName);
}
return tableName;
}
return super.getTableName();
}
public String getTableNameEnc(String tableName) {
Class<T> entityClass = getEntityClass();
if (entityClass != null) {
TableInfo tableInfo = TableHelper.get(entityClass);
if (tableInfo != null) {
if (dynamicTableName) {
return tableFunc.apply(tableInfo.getTableName());
}
return tableInfo.getTableName();
}
}
String decode;
try {
decode = URLDecoder.decode(tableName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
if (dynamicTableName) {
return tableFunc.apply(decode);
}
return decode;
}
@Override
protected String columnsToString(Column... columns) {
return Arrays.stream(columns).map(this::columnToString)
.collect(joining(StringPool.COMMA));
}
@Override
protected String columnToString(Column column) {
String pf = column.getAlias().get();
if (Objects.nonNull(pf)) {
return pf + StringPool.DOT + getCache(column).getColumn();
}
return this.aptIndex.get(column.getRoot()) + StringPool.DOT + getCache(column).getColumn();
}
protected SelectCache getCache(Column fn) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(fn.getClazz());
return cacheMap.get(fn.getProperty());
}
/**
* 关闭副表逻辑删除
* <p>
* 副表逻辑删除默认在where语句中
* 但有时候需要让它出现在on语句中, 这两种写法区别还是很大的
* 所以可以关闭副表逻辑删除, 通过on语句多条件, 自己实现on语句的逻辑删除
*/
public Children disableSubLogicDel() {
this.subLogicSql = false;
return typedThis;
}
public Children enableSubLogicDel() {
this.subLogicSql = true;
return typedThis;
}
/**
* 关闭主表逻辑删除
*/
public Children disableLogicDel() {
this.logicSql = false;
return typedThis;
}
public Children enableLogicDel() {
this.logicSql = true;
return typedThis;
}
/**
* 副表部分逻辑删除支持
*/
public String getSubLogicSql() {
if (subLogicSql && logicDelType == LogicDelTypeEnum.WHERE) {
if (aptIndex.isEmpty()) {
return StringPool.EMPTY;
}
return aptIndex.keyList().stream().map(key -> LogicInfoUtils.getLogicInfoApt(key.getColumnClass(), this.aptIndex.get(key)))
.collect(Collectors.joining(StringPool.SPACE));
}
return StringPool.EMPTY;
}
/**
* 主表部分逻辑删除支持
*/
public boolean getLogicSql() {
return this.logicSql;
}
/**
* 调整逻辑删除位置为ON语句
*/
public Children logicDelToOn() {
this.logicDelType = LogicDelTypeEnum.ON;
return typedThis;
}
/**
* 调整逻辑删除位置为WHERE语句
*/
public Children logicDelToWhere() {
this.logicDelType = LogicDelTypeEnum.WHERE;
return typedThis;
}
/**
* 获取连表部分语句
*/
public String getFrom() {
if (StrUtils.isBlank(from.getStringValue())) {
StringBuilder value = new StringBuilder();
for (Children wrapper : onWrappers) {
if (StrUtils.isBlank(wrapper.from.getStringValue())) {
if (this.subLogicSql && this.logicDelType == LogicDelTypeEnum.ON) {
TableInfo tableInfo = TableHelper.getAssert(wrapper.getJoinClass());
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo)) {
wrapper.appendSqlSegments(APPLY, () -> LogicInfoUtils.getLogicInfoNoAnd(
wrapper.getIndex(), wrapper.getJoinClass(), wrapper.isHasAlias(), wrapper.getAlias()
));
}
}
value.append(StringPool.SPACE)
.append(wrapper.getKeyWord())
.append(StringPool.SPACE)
.append(wrapper.getTableName())
.append(StringPool.SPACE)
.append(wrapper.hasAlias ? wrapper.alias : (wrapper.alias + wrapper.getIndex()))
.append(Constant.ON)
.append(wrapper.getExpression().getNormal().getSqlSegment());
} else {
value.append(StringPool.SPACE)
.append(wrapper.getKeyWord())
.append(StringPool.SPACE)
.append(wrapper.from.getStringValue())
.append(StringPool.SPACE);
}
}
from.setStringValue(value.toString());
}
return from.getStringValue();
}
/**
* 检验表是否已连接
*/
public boolean checkJoinTable(Class<?> clazz) {
return onWrappers.stream().anyMatch(wrapper -> {
if (Objects.equals(wrapper.getJoinClass(), clazz)) {
return true;
} else {
TableInfo info = TableHelper.getAssert(clazz);
String tableName = info.getTableName();
return Optional.ofNullable(wrapper.from.getStringValue())
.map(w -> w.contains(Constant.JOIN + StringPool.SPACE + tableName + StringPool.SPACE))
.orElse(false);
}
});
}
/**
* 内部调用, 不建议使用
*/
@Override
public <R> Children join(String keyWord, BaseColumn<R> baseColumn, MFunction<AptAbstractWrapper<T, ?>> function) {
Integer oldIndex = this.getIndex();
int newIndex = tableIndex;
TableInfo info = TableHelper.getAssert(baseColumn.getColumnClass());
Children instance = instance(newIndex, keyWord, baseColumn.getColumnClass(), info.getTableName());
instance.isMain = false;
onWrappers.add(instance);
if (StrUtils.isBlank(baseColumn.getAlias())) {
aptIndex.put(baseColumn, subTableAlias + newIndex);
instance.alias = subTableAlias;
instance.hasAlias = false;
} else {
aptIndex.put(baseColumn, baseColumn.getAlias());
instance.alias = baseColumn.getAlias();
instance.hasAlias = true;
}
tableIndex++;
function.apply(instance);
return typedThis;
}
/**
* 自定义关键词连接
*
* @param keyWord 连表关键词
* @param condition 条件
* @param joinSql sql
*/
@Override
public Children join(String keyWord, boolean condition, String joinSql, Object... objects) {
if (condition) {
Children wrapper = instanceEmpty();
wrapper.from.setStringValue(formatSqlMaybeWithParam(joinSql, objects));
wrapper.keyWord = keyWord;
onWrappers.add(wrapper);
}
return typedThis;
}
/**
* 是否使用默认注解 {@link OrderBy} 排序
*
* @return true 使用 false 不使用
*/
public boolean isUseAnnotationOrderBy() {
final String _sqlSegment = this.getSqlSegment();
if (StrUtils.isBlank(_sqlSegment)) {
return true;
}
final String _sqlSegmentToUpperCase = _sqlSegment.toUpperCase();
return !(_sqlSegmentToUpperCase.contains(Constants.ORDER_BY)
|| _sqlSegmentToUpperCase.contains(Constants.LIMIT));
}
/**
* 必要的初始化
*/
protected void initNeed() {
paramNameSeq = new AtomicInteger(0);
paramNameValuePairs = new HashMap<>(16);
expression = new MergeSegments();
lastSql = SharedString.emptyString();
sqlComment = SharedString.emptyString();
sqlFirst = SharedString.emptyString();
aptIndex = new TableMap(this.baseColumn, this.alias);
}
@Override
public void clear() {
super.clear();
this.alias = ConfigProperties.tableAlias;
this.resultMap = false;
this.resultMapCollection = false;
this.pageInfo = null;
this.pageByMain = false;
this.tableIndex = 1;
this.dynamicTableName = false;
this.tableFunc = null;
this.logicDelType = ConfigProperties.logicDelType;
this.from.toEmpty();
this.hasAlias = false;
this.keyWord = null;
this.logicSql = true;
this.isMain = true;
this.checkSqlInjection = false;
this.onWrappers.clear();
this.aptIndex.clear();
}
}

View File

@ -1,361 +0,0 @@
package com.github.yulichang.extension.apt;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.extension.apt.interfaces.Query;
import com.github.yulichang.extension.apt.interfaces.QueryLabel;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.extension.apt.toolkit.AptWrapperUtils;
import com.github.yulichang.extension.apt.toolkit.AptWrappers;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.TableMap;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import com.github.yulichang.wrapper.interfaces.Chain;
import com.github.yulichang.wrapper.interfaces.MBiPredicate;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.interfaces.SelectWrapper;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.segments.*;
import lombok.Getter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Lambda 语法使用 Wrapper
*
* @author yulichang
* @since 1.5.0
*/
@SuppressWarnings("unused")
public class AptQueryWrapper<T> extends AptAbstractWrapper<T, AptQueryWrapper<T>> implements
Query<AptQueryWrapper<T>>, QueryLabel<AptQueryWrapper<T>>, Chain<T>, SelectWrapper<T, AptQueryWrapper<T>> {
/**
* 查询字段 sql
*/
private SharedString sqlSelect = new SharedString();
/**
* 是否 select distinct
*/
private boolean selectDistinct = false;
/**
* 查询的字段
*/
@Getter
private final List<Select> selectColumns = new ArrayList<>();
/**
* 映射关系
*/
@Getter
private final List<Label<?>> resultMapMybatisLabel = new ArrayList<>();
/**
* union sql
*/
private SharedString unionSql;
/**
* 自定义wrapper索引
*/
private AtomicInteger wrapperIndex;
/**
* 自定义wrapper
*/
@Getter
private Map<String, Wrapper<?>> wrapperMap;
/**
* 推荐使用此构造方法
*/
public AptQueryWrapper(BaseColumn<T> baseColumn) {
super(baseColumn);
}
public AptQueryWrapper(BaseColumn<T> baseColumn, T entity) {
super(baseColumn, entity);
}
/**
* 不建议直接 new 该实例使用 JoinWrappers.lambda(UserDO.class)
*/
protected AptQueryWrapper(T entity, BaseColumn<T> baseColumn, SharedString sqlSelect, AtomicInteger paramNameSeq,
Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments, SharedString paramAlias,
SharedString lastSql, SharedString sqlComment, SharedString sqlFirst,
TableMap aptIndex, Integer index, String keyWord, Class<?> joinClass, String tableName,
MBiPredicate<Object, IfExistsSqlKeyWordEnum> IfExists) {
super(baseColumn);
super.setEntity(entity);
super.setEntityClass(baseColumn.getColumnClass());
this.baseColumn = baseColumn;
this.paramNameSeq = paramNameSeq;
this.paramNameValuePairs = paramNameValuePairs;
this.expression = mergeSegments;
this.sqlSelect = sqlSelect;
this.paramAlias = paramAlias;
this.lastSql = lastSql;
this.sqlComment = sqlComment;
this.sqlFirst = sqlFirst;
if (aptIndex != null) {
this.aptIndex = aptIndex;
}
this.index = index;
this.keyWord = keyWord;
this.joinClass = joinClass;
this.tableName = tableName;
this.ifExists = IfExists;
}
/**
* sql去重
* select distinct
*/
public AptQueryWrapper<T> distinct() {
this.selectDistinct = true;
return typedThis;
}
@Override
public List<Select> getSelectColum() {
return this.selectColumns;
}
@Override
public void addLabel(Label<?> label, boolean isCollection) {
if (isCollection) {
this.resultMapCollection = true;
}
this.resultMap = true;
this.resultMapMybatisLabel.add(label);
}
@Override
public AptQueryWrapper<T> getChildren() {
return typedThis;
}
/**
* 设置查询字段
*
* @param columns 字段数组
* @return children
*/
public final AptQueryWrapper<T> select(Column... columns) {
if (ArrayUtils.isNotEmpty(columns)) {
for (Column s : columns) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(s.getClazz());
SelectCache cache = cacheMap.get(s.getProperty());
getSelectColum().add(new SelectApt(cache, s));
}
}
return typedThis;
}
/**
* 查询实体类全部字段
*/
@Override
public final <E> AptQueryWrapper<T> selectAll(BaseColumn<E> baseColumn, Column... exclude) {
return Query.super.selectAll(baseColumn, exclude);
}
/**
* 查询主表全部字段
* <p>
* 需要使用 使用 JoinWrappers.lambda(clazz) 或者 new MPJLambdaQueryWrapper&lt;&lt;(clazz) 构造
*
* @return children
*/
@Override
public AptQueryWrapper<T> selectAll() {
Assert.notNull(getEntityClass(), "使用 AptWrappers.query(clazz) 或者 new JoinAptQueryWrapper<>(BaseColum)");
return selectAll(getBaseColumn());
}
@Override
public AptQueryWrapper<T> selectFunc(String sql, MFunction<AptConsumer> column, String alias) {
AptConsumer apply = column.apply(new AptConsumer());
String formatSql;
if (ArrayUtils.isEmpty(apply.getValues())) {
formatSql = sql;
} else {
formatSql = formatSqlMaybeWithParam(sql, apply.getValues());
}
getSelectColum().add(new SelectApt(apply.getColumns(), () -> formatSql, alias));
return typedThis;
}
public <E, F> AptQueryWrapper<T> selectSub(BaseColumn<E> baseColumn, Consumer<AptQueryWrapper<E>> consumer, SFunction<F, ?> alias) {
return selectSub(baseColumn, consumer, LambdaUtils.getName(alias));
}
/**
* 子查询
*/
public <E, F> AptQueryWrapper<T> selectSub(BaseColumn<E> baseColumn, Consumer<AptQueryWrapper<E>> consumer, String alias) {
AptQueryWrapper<E> wrapper = new AptQueryWrapper<E>(null, baseColumn, SharedString.emptyString(),
paramNameSeq, paramNameValuePairs, new MergeSegments(), new SharedString(this.paramAlias
.getStringValue()), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
null, null, null, null, null, ifExists) {
};
wrapper.aptIndex.setParent(this.aptIndex);
if (null == baseColumn.getAlias()) {
wrapper.alias = ConfigProperties.subQueryAlias;
wrapper.aptIndex.setRootAlias(ConfigProperties.subQueryAlias);
}
wrapper.subTableAlias = ConfigProperties.subQueryAlias;
consumer.accept(wrapper);
addCustomWrapper(wrapper);
this.selectColumns.add(new SelectSub(() -> AptWrapperUtils.buildSubSqlByWrapper(baseColumn.getColumnClass(), wrapper, alias), hasAlias, this.alias, alias));
return typedThis;
}
/**
* union
* <p>
* wrapper.union(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @param baseColumn union语句的主表类型
* @since 1.4.8
*/
public <U> AptQueryWrapper<T> union(BaseColumn<U> baseColumn, Consumer<AptQueryWrapper<U>> consumer) {
AptQueryWrapper<U> unionWrapper = AptWrappers.query(baseColumn);
addCustomWrapper(unionWrapper);
consumer.accept(unionWrapper);
String sb = " UNION " + AptWrapperUtils.buildUnionSqlByWrapper(baseColumn.getColumnClass(), unionWrapper);
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
/**
* union
* <p>
* wrapper.unionAll(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @param baseColumn union语句的主表类型
* @since 1.4.8
*/
public <U> AptQueryWrapper<T> unionAll(BaseColumn<U> baseColumn, Consumer<AptQueryWrapper<U>> consumer) {
AptQueryWrapper<U> unionWrapper = AptWrappers.query(baseColumn);
addCustomWrapper(unionWrapper);
consumer.accept(unionWrapper);
String sb = " UNION ALL " + AptWrapperUtils.buildUnionSqlByWrapper(baseColumn.getColumnClass(), unionWrapper);
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
private void addCustomWrapper(AptQueryWrapper<?> wrapper) {
if (Objects.isNull(wrapperIndex)) {
wrapperIndex = new AtomicInteger(0);
}
int index = wrapperIndex.incrementAndGet();
if (Objects.isNull(wrapperMap)) {
wrapperMap = new HashMap<>();
}
String key = "ew" + index;
wrapper.setParamAlias(wrapper.getParamAlias() + ".wrapperMap." + key);
wrapperMap.put(key, wrapper);
}
/**
* 查询条件 SQL 片段
*/
@Override
public String getSqlSelect() {
if (StrUtils.isBlank(sqlSelect.getStringValue()) && CollectionUtils.isNotEmpty(selectColumns)) {
String s = selectColumns.stream().map(i -> {
if (i.isStr()) {
return i.getColumn();
}
if (i.isFunc()) {
return String.format(i.getFunc().getSql(), Arrays.stream(i.getColumns()).map(c ->
this.aptIndex.get(c.getRoot()) + StringPool.DOT + i.getColumn()).toArray()) + Constant.AS + i.getAlias();
} else {
String prefix;
if (null == i.getTableAlias() && null != i.getBaseColumn()) {
prefix = this.aptIndex.get(i.getBaseColumn());
} else {
prefix = i.getTableAlias();
}
String col = prefix + StringPool.DOT + i.getColumn();
return i.isHasAlias() ? col + Constants.AS + i.getAlias() : col;
}
}).collect(Collectors.joining(StringPool.COMMA));
sqlSelect.setStringValue(s);
}
return sqlSelect.getStringValue();
}
@Override
public String getUnionSql() {
return Optional.ofNullable(unionSql).map(SharedString::getStringValue).orElse(StringPool.EMPTY);
}
public boolean getSelectDistinct() {
return selectDistinct;
}
/**
* 用于生成嵌套 sql
* <p> sqlSelect 不向下传递</p>
*/
@Override
protected AptQueryWrapper<T> instance() {
return instance(index, null, null, null);
}
@Override
protected AptQueryWrapper<T> instanceEmpty() {
return new AptQueryWrapper<>(getBaseColumn());
}
@Override
protected AptQueryWrapper<T> instance(Integer index, String keyWord, Class<?> joinClass, String tableName) {
return new AptQueryWrapper<>(getEntity(), baseColumn, null, paramNameSeq, paramNameValuePairs,
new MergeSegments(), this.paramAlias, SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
this.aptIndex, index, keyWord, joinClass, tableName, ifExists);
}
@Override
public void clear() {
super.clear();
selectDistinct = false;
sqlSelect.toNull();
selectColumns.clear();
wrapperIndex = new AtomicInteger(0);
if (Objects.nonNull(wrapperMap)) wrapperMap.clear();
if (Objects.nonNull(unionSql)) unionSql.toEmpty();
resultMapMybatisLabel.clear();
ifExists = ConfigProperties.ifExists;
}
}

View File

@ -1,98 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.github.yulichang.extension.apt.matedata.Column;
import java.io.Serializable;
/**
* 将原来的泛型R改成Column
* <p>
* {@link com.baomidou.mybatisplus.core.conditions.interfaces.Compare}
*/
@SuppressWarnings("unused")
public interface Compare<Children> extends Serializable {
default Children eq(Column column, Object val) {
return eq(true, column, val);
}
Children eq(boolean condition, Column column, Object val);
default Children ne(Column column, Object val) {
return ne(true, column, val);
}
Children ne(boolean condition, Column column, Object val);
default Children gt(Column column, Object val) {
return gt(true, column, val);
}
Children gt(boolean condition, Column column, Object val);
default Children ge(Column column, Object val) {
return ge(true, column, val);
}
Children ge(boolean condition, Column column, Object val);
default Children lt(Column column, Object val) {
return lt(true, column, val);
}
Children lt(boolean condition, Column column, Object val);
default Children le(Column column, Object val) {
return le(true, column, val);
}
Children le(boolean condition, Column column, Object val);
default Children between(Column column, Object val1, Object val2) {
return between(true, column, val1, val2);
}
Children between(boolean condition, Column column, Object val1, Object val2);
default Children notBetween(Column column, Object val1, Object val2) {
return notBetween(true, column, val1, val2);
}
Children notBetween(boolean condition, Column column, Object val1, Object val2);
default Children like(Column column, Object val) {
return like(true, column, val);
}
Children like(boolean condition, Column column, Object val);
default Children notLike(Column column, Object val) {
return notLike(true, column, val);
}
Children notLike(boolean condition, Column column, Object val);
default Children likeLeft(Column column, Object val) {
return likeLeft(true, column, val);
}
Children likeLeft(boolean condition, Column column, Object val);
default Children notLikeLeft(Column column, Object val) {
return notLikeLeft(true, column, val);
}
Children notLikeLeft(boolean condition, Column column, Object val);
default Children likeRight(Column column, Object val) {
return likeRight(true, column, val);
}
Children likeRight(boolean condition, Column column, Object val);
default Children notLikeRight(Column column, Object val) {
return notLikeRight(true, column, val);
}
Children notLikeRight(boolean condition, Column column, Object val);
}

View File

@ -1,66 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import java.util.function.BiPredicate;
/**
* {@link com.baomidou.mybatisplus.core.conditions.interfaces.Compare}
*
* @author yulichang
* @since 1.4.9
*/
@SuppressWarnings("unused")
public interface CompareIfExists<Children> extends Compare<Children> {
BiPredicate<Object, IfExistsSqlKeyWordEnum> getIfExists();
default Children eqIfExists(Column column, Object val) {
return eq(getIfExists().test(val, IfExistsSqlKeyWordEnum.EQ), column, val);
}
default Children neIfExists(Column column, Object val) {
return ne(getIfExists().test(val, IfExistsSqlKeyWordEnum.NE), column, val);
}
default Children gtIfExists(Column column, Object val) {
return gt(getIfExists().test(val, IfExistsSqlKeyWordEnum.GT), column, val);
}
default Children geIfExists(Column column, Object val) {
return ge(getIfExists().test(val, IfExistsSqlKeyWordEnum.GE), column, val);
}
default Children ltIfExists(Column column, Object val) {
return lt(getIfExists().test(val, IfExistsSqlKeyWordEnum.LT), column, val);
}
default Children leIfExists(Column column, Object val) {
return le(getIfExists().test(val, IfExistsSqlKeyWordEnum.LE), column, val);
}
default Children likeIfExists(Column column, Object val) {
return like(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE), column, val);
}
default Children notLikeIfExists(Column column, Object val) {
return notLike(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE), column, val);
}
default Children likeLeftIfExists(Column column, Object val) {
return likeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_LEFT), column, val);
}
default Children notLikeLeftIfExists(Column column, Object val) {
return notLikeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_LEFT), column, val);
}
default Children likeRightIfExists(Column column, Object val) {
return likeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_RIGHT), column, val);
}
default Children notLikeRightIfExists(Column column, Object val) {
return notLikeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_RIGHT), column, val);
}
}

View File

@ -1,191 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.github.yulichang.extension.apt.matedata.Column;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
/**
* 将原来的泛型R改成Column
* <p>
* copy {@link com.baomidou.mybatisplus.core.conditions.interfaces.Func}
*/
@SuppressWarnings("unused")
public interface Func<Children> extends FuncLambda<Children> {
default Children isNull(Column column) {
return isNull(true, column);
}
Children isNull(boolean condition, Column column);
default Children isNotNull(Column column) {
return isNotNull(true, column);
}
Children isNotNull(boolean condition, Column column);
default Children in(Column column, Collection<?> coll) {
return in(true, column, coll);
}
Children in(boolean condition, Column column, Collection<?> coll);
default Children in(Column column, Object... values) {
return in(true, column, values);
}
Children in(boolean condition, Column column, Object... values);
default Children notIn(Column column, Collection<?> coll) {
return notIn(true, column, coll);
}
Children notIn(boolean condition, Column column, Collection<?> coll);
default Children notIn(Column column, Object... values) {
return notIn(true, column, values);
}
Children notIn(boolean condition, Column column, Object... values);
default Children inSql(Column column, String inValue) {
return inSql(true, column, inValue);
}
Children inSql(boolean condition, Column column, String inValue);
default Children notInSql(Column column, String inValue) {
return notInSql(true, column, inValue);
}
Children notInSql(boolean condition, Column column, String inValue);
default Children gtSql(Column column, String inValue) {
return gtSql(true, column, inValue);
}
Children gtSql(boolean condition, Column column, String inValue);
default Children geSql(Column column, String inValue) {
return geSql(true, column, inValue);
}
Children geSql(boolean condition, Column column, String inValue);
default Children ltSql(Column column, String inValue) {
return ltSql(true, column, inValue);
}
Children ltSql(boolean condition, Column column, String inValue);
default Children leSql(Column column, String inValue) {
return leSql(true, column, inValue);
}
Children leSql(boolean condition, Column column, String inValue);
default Children eqSql(Column column, String inValue) {
return eqSql(true, column, inValue);
}
Children eqSql(boolean condition, Column column, String inValue);
default Children groupBy(Column column) {
return groupBy(true, column);
}
default Children groupBy(List<Column> column) {
return groupBy(true, column);
}
Children groupBy(boolean condition, List<Column> columns);
default Children groupBy(Column column, Column... columns) {
return groupBy(true, column, columns);
}
Children groupBy(boolean condition, Column column, Column... columns);
default Children orderByAsc(Column column) {
return orderByAsc(true, column);
}
default Children orderByAsc(List<Column> columns) {
return orderByAsc(true, columns);
}
Children orderByAsc(boolean condition, List<Column> columns);
default Children orderByAsc(Column column, Column... columns) {
return orderByAsc(true, column, columns);
}
default Children orderByAsc(boolean condition, Column column, Column... columns) {
return orderBy(condition, true, column, columns);
}
default Children orderByDesc(Column column) {
return orderByDesc(true, column);
}
default Children orderByDesc(List<Column> columns) {
return orderByDesc(true, columns);
}
Children orderByDesc(boolean condition, List<Column> columns);
default Children orderByDesc(Column column, Column... columns) {
return orderByDesc(true, column, columns);
}
default Children orderByDesc(boolean condition, Column column, Column... columns) {
return orderBy(condition, false, column, columns);
}
Children orderBy(boolean condition, boolean isAsc, Column column, Column... columns);
default Children having(String sqlHaving, Object... params) {
return having(true, sqlHaving, params);
}
/**
* HAVING ( sql语句 )
* <p>例1: having("sum(age) &gt; 10")</p>
* <p>例2: having("sum(age) &gt; {0}", 10)</p>
*
* @param condition 执行条件
* @param sqlHaving sql 语句
* @param params 参数数组
* @return children
*/
Children having(boolean condition, String sqlHaving, Object... params);
default Children func(Consumer<Children> consumer) {
return func(true, consumer);
}
/**
* 消费函数
*
* @param consumer 消费函数
* @return children
* @since 3.3.1
*/
default Children func(boolean condition, Consumer<Children> consumer) {
return func(condition, consumer, null);
}
Children func(boolean condition, Consumer<Children> consumer, Consumer<Children> consumerElse);
}

View File

@ -1,61 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import java.io.Serializable;
import java.util.List;
/**
* 将原来的泛型R改成SFunction<X,?>
* <p>
* copy {@link com.baomidou.mybatisplus.core.conditions.interfaces.Func}
*/
@SuppressWarnings({"unused", "unchecked"})
public interface FuncLambda<Children> extends Serializable {
default <X> Children groupBy(SFunction<X, ?> column) {
return groupBy(true, column);
}
default <X> Children groupByLambda(List<SFunction<X, ?>> column) {
return groupByLambda(true, column);
}
<X> Children groupByLambda(boolean condition, List<SFunction<X, ?>> columns);
<X> Children groupBy(SFunction<X, ?> column, SFunction<X, ?>... columns);
<X> Children groupBy(boolean condition, SFunction<X, ?> column, SFunction<X, ?>... columns);
default <X> Children orderByAsc(SFunction<X, ?> column) {
return orderByAsc(true, column);
}
default <X> Children orderByAscLambda(List<SFunction<X, ?>> columns) {
return orderByAscLambda(true, columns);
}
<X> Children orderByAscLambda(boolean condition, List<SFunction<X, ?>> columns);
<X> Children orderByAsc(SFunction<X, ?> column, SFunction<X, ?>... columns);
<X> Children orderByAsc(boolean condition, SFunction<X, ?> column, SFunction<X, ?>... columns);
default <X> Children orderByDesc(SFunction<X, ?> column) {
return orderByDesc(true, column);
}
default <X> Children orderByDescLambda(List<SFunction<X, ?>> columns) {
return orderByDescLambda(true, columns);
}
<X> Children orderByDescLambda(boolean condition, List<SFunction<X, ?>> columns);
<X> Children orderByDesc(SFunction<X, ?> column, SFunction<X, ?>... columns);
<X> Children orderByDesc(boolean condition, SFunction<X, ?> column, SFunction<X, ?>... columns);
<X> Children orderBy(boolean condition, boolean isAsc, SFunction<X, ?> column, SFunction<X, ?>... columns);
}

View File

@ -1,101 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.github.yulichang.extension.apt.matedata.Column;
import java.io.Serializable;
/**
* 将原来的泛型R改成Column, Object改为Column
* 以及移除不会在ON语句中出现的条件 比如like相关 保留原来的like 只是不太可能会出现 on a.id like b.id 所以不会支持这种写法
* <p>
* {@link com.baomidou.mybatisplus.core.conditions.interfaces.Compare}
*
* @since 1.1.8
*/
@SuppressWarnings("unused")
public interface OnCompare<Children> extends Serializable {
default Children eq(Column column, Column val) {
return eq(true, column, val);
}
/**
* 等于 =
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children eq(boolean condition, Column column, Column val);
default Children ne(Column column, Column val) {
return ne(true, column, val);
}
/**
* 不等于 &lt;&gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ne(boolean condition, Column column, Column val);
default Children gt(Column column, Column val) {
return gt(true, column, val);
}
/**
* 大于 &gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children gt(boolean condition, Column column, Column val);
default Children ge(Column column, Column val) {
return ge(true, column, val);
}
/**
* 大于等于 &gt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ge(boolean condition, Column column, Column val);
default Children lt(Column column, Column val) {
return lt(true, column, val);
}
/**
* 小于 &lt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children lt(boolean condition, Column column, Column val);
default Children le(Column column, Column val) {
return le(true, column, val);
}
/**
* 小于等于 &lt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children le(boolean condition, Column column, Column val);
}

View File

@ -1,280 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.enums.BaseFuncEnum;
import com.github.yulichang.wrapper.enums.DefaultFuncEnum;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.segments.*;
import java.io.Serializable;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* 参考 {@link com.baomidou.mybatisplus.core.conditions.query.Query}
*
* @author yulichang
*/
@SuppressWarnings({"unused"})
public interface Query<Children> extends Serializable {
List<Select> getSelectColum();
Children getChildren();
/**
* 过滤查询的字段信息
* <p>例1: 只要 java 字段名以 "test" 开头的 -> select(i -> i.getProperty().startsWith("test"))</p>
* <p>例2: 只要 java 字段属性是 CharSequence 类型的 -> select(TableFieldInfo::isCharSequence)</p>
* <p>例3: 只要 java 字段没有填充策略的 -> select(i -> i.getFieldFill() == FieldFill.DEFAULT)</p>
* <p>例4: 要全部字段 -> select(i -> true)</p>
* <p>例5: 只要主键字段 -> select(i -> false)</p>
*
* @param predicate 过滤方式
* @return children
*/
default <E> Children selectFilter(BaseColumn<E> baseColumn, Predicate<SelectCache> predicate) {
TableInfo info = TableHelper.getAssert(baseColumn.getColumnClass());
List<SelectCache> cacheList = ColumnCache.getListField(baseColumn.getColumnClass());
cacheList.stream().filter(SelectCache::isSelect).filter(predicate).collect(Collectors.toList()).forEach(
i -> getSelectColum().add(new SelectApt(i, baseColumn)));
return getChildren();
}
<E> Children select(Column... columns);
/**
* String 查询
*
* @param columns
*/
default Children select(String... columns) {
getSelectColum().add(new SelectString(String.join(StringPool.COMMA, columns), null));
return getChildren();
}
/**
* String 查询
*
* @param column
*/
default <E> Children selectAs(String column, SFunction<E, ?> alias) {
String name = LambdaUtils.getName(alias);
getSelectColum().add(new SelectString(column + Constant.AS + name, name));
return getChildren();
}
/**
* String 查询
*
* @param column
*/
default <X> Children selectAs(String index, Column column, SFunction<X, ?> alias) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(column.getClazz());
SelectCache cache = cacheMap.get(column.getProperty());
String name = LambdaUtils.getName(alias);
getSelectColum().add(new SelectApt(cache, column, name));
return getChildren();
}
default <E> Children selectAsClass(BaseColumn<E> baseColumn, Class<?> tag) {
Map<String, SelectCache> normalMap = ColumnCache.getMapField(baseColumn.getColumnClass());
List<FieldCache> fieldList = MPJReflectionKit.getFieldList(tag);
for (FieldCache cache : fieldList) {
if (normalMap.containsKey(cache.getField().getName())) {
SelectCache selectCache = normalMap.get(cache.getField().getName());
if (selectCache.isSelect()) {
getSelectColum().add(new SelectApt(selectCache, baseColumn));
}
}
}
return getChildren();
}
/**
* ignore
*/
default <X> Children selectAs(Column column, SFunction<X, ?> alias) {
return selectAs(column, LambdaUtils.getName(alias));
}
/**
* 别名查询
*/
default Children selectAs(Column column, String alias) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(column.getClazz());
SelectCache cache = cacheMap.get(column.getProperty());
getSelectColum().add(new SelectApt(cache, column, alias));
return getChildren();
}
/**
* 查询实体类全部字段
*/
default <E> Children selectAll(BaseColumn<E> baseColumn) {
getSelectColum().addAll(ColumnCache.getListField(baseColumn.getColumnClass()).stream().filter(SelectCache::isSelect).map(i ->
new SelectApt(i, baseColumn)).collect(Collectors.toList()));
return getChildren();
}
/**
* 查询实体类全部字段
*
* @param baseColumn 查询的实体类
* @param exclude 排除字段
*/
default <E> Children selectAll(BaseColumn<E> baseColumn, Column... exclude) {
Set<String> excludeSet = Arrays.stream(exclude).map(i ->
i.getProperty().toUpperCase(Locale.ENGLISH)).collect(Collectors.toSet());
getSelectColum().addAll(ColumnCache.getListField(baseColumn.getColumnClass()).stream().filter(e -> e.isSelect() &&
!excludeSet.contains(e.getColumProperty().toUpperCase(Locale.ENGLISH))).map(i ->
new SelectApt(i, baseColumn)).collect(Collectors.toList()));
return getChildren();
}
/**
* select sql 片段
*/
String getSqlSelect();
/**
* 聚合函数查询
* <p>
* wrapper.selectFunc(() -> "COUNT(%s)", "t.id", "total");
* <p>
* lambda
* wrapper.selectFunc(() -> "COUNT(%s)", UserDO::getId, UserDTO::getTotal);
*
* @param funcEnum 函数枚举 {@link DefaultFuncEnum}
* @param column 函数作用的字段
* @param alias 别名
*/
default Children selectFunc(BaseFuncEnum funcEnum, Column column, String alias) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(column.getClazz());
getSelectColum().add(new SelectApt(cacheMap.get(column.getProperty()), column, funcEnum, alias));
return getChildren();
}
default <X> Children selectFunc(BaseFuncEnum funcEnum, Column column, SFunction<X, ?> alias) {
return selectFunc(funcEnum, column, LambdaUtils.getName(alias));
}
default Children selectFunc(BaseFuncEnum funcEnum, Column column) {
return selectFunc(funcEnum, column, column.getProperty());
}
Children selectFunc(String sql, MFunction<AptConsumer> column, String alias);
default <S> Children selectFunc(String sql, MFunction<AptConsumer> column, SFunction<S, ?> alias) {
return selectFunc(sql, column, LambdaUtils.getName(alias));
}
/* 默认聚合函数扩展 */
/**
* SUM()
*/
default Children selectSum(Column column) {
return selectFunc(DefaultFuncEnum.SUM, column);
}
default <X> Children selectSum(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.SUM, column, alias);
}
default Children selectSum(Column column, String alias) {
return selectFunc(DefaultFuncEnum.SUM, column, alias);
}
/**
* COUNT()
*/
default Children selectCount(Column column) {
return selectFunc(DefaultFuncEnum.COUNT, column);
}
default <X> Children selectCount(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
default Children selectCount(Column column, String alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
/**
* MAX()
*/
default Children selectMax(Column column) {
return selectFunc(DefaultFuncEnum.MAX, column);
}
default <X> Children selectMax(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.MAX, column, alias);
}
default Children selectMax(Column column, String alias) {
return selectFunc(DefaultFuncEnum.MAX, column, alias);
}
/**
* MIN()
*/
default Children selectMin(Column column) {
return selectFunc(DefaultFuncEnum.MIN, column);
}
default <X> Children selectMin(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.MIN, column, alias);
}
default Children selectMin(Column column, String alias) {
return selectFunc(DefaultFuncEnum.MIN, column, alias);
}
/**
* MIN()
*/
default Children selectAvg(Column column) {
return selectFunc(DefaultFuncEnum.AVG, column);
}
default <X> Children selectAvg(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.AVG, column, alias);
}
default Children selectAvg(Column column, String alias) {
return selectFunc(DefaultFuncEnum.AVG, column, alias);
}
/**
* LEN()
*/
default Children selectLen(Column column) {
return selectFunc(DefaultFuncEnum.LEN, column);
}
default <X> Children selectLen(Column column, SFunction<X, ?> alias) {
return selectFunc(DefaultFuncEnum.LEN, column, alias);
}
default Children selectLen(Column column, String alias) {
return selectFunc(DefaultFuncEnum.LEN, column, alias);
}
}

View File

@ -1,91 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.query.interfaces.StringJoin;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.extension.apt.AptAbstractWrapper;
import com.github.yulichang.wrapper.interfaces.MFunction;
/**
* @author yulichang
*/
@SuppressWarnings("unused")
public interface QueryJoin<Children, Entity> extends MPJBaseJoin<Entity>, StringJoin<Children, Entity> {
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default <T> Children leftJoin(BaseColumn<T> clazz, Column left, Column right) {
return join(Constant.LEFT_JOIN, clazz, left, right);
}
/**
* left join 多条件
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param function 条件`
*/
default <T> Children leftJoin(BaseColumn<T> clazz, MFunction<AptAbstractWrapper<Entity, ?>> function) {
return join(Constant.LEFT_JOIN, clazz, function);
}
/**
* ignore 参考 left join
*/
default <T> Children rightJoin(BaseColumn<T> clazz, Column left, Column right) {
return join(Constant.RIGHT_JOIN, clazz, left, right);
}
/**
* ignore 参考 left join
*/
default <T> Children rightJoin(BaseColumn<T> clazz, MFunction<AptAbstractWrapper<Entity, ?>> function) {
return join(Constant.RIGHT_JOIN, clazz, function);
}
/**
* ignore 参考 left join
*/
default <T> Children innerJoin(BaseColumn<T> clazz, Column left, Column right) {
return join(Constant.INNER_JOIN, clazz, left, right);
}
/**
* ignore 参考 left join
*/
default <T> Children innerJoin(BaseColumn<T> clazz, MFunction<AptAbstractWrapper<Entity, ?>> function) {
return join(Constant.INNER_JOIN, clazz, function);
}
/**
* 自定义连表关键词
* 调用此方法 keyword 前后需要带空格 比如 " LEFT JOIN " " RIGHT JOIN "
* <p>
* 查询基类 可以直接调用此方法实现以上所有功能
*
* @param keyWord 连表关键字
* @param clazz 连表实体类
* @param left 关联条件
* @param right 扩展 用于关联表的 select where
*/
default <T> Children join(String keyWord, BaseColumn<T> clazz, Column left, Column right) {
return join(keyWord, clazz, on -> on.eq(left, right));
}
/**
* 内部使用, 不建议直接调用
*/
<T> Children join(String keyWord, BaseColumn<T> clazz, MFunction<AptAbstractWrapper<Entity, ?>> function);
}

View File

@ -1,172 +0,0 @@
package com.github.yulichang.extension.apt.interfaces;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.extension.apt.resultmap.MybatisLabel;
import com.github.yulichang.extension.apt.resultmap.MybatisLabelFree;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.Label;
import java.util.Collection;
import java.util.Map;
/**
* 对一或对多查询
*
* @author yulichang
* @since 1.3.0
*/
@SuppressWarnings({"unchecked", "unused", "DuplicatedCode"})
public interface QueryLabel<Children> {
void addLabel(Label<?> label, boolean isCollection);
Children getChildren();
/**
* 一对多查询 调用此方法必需要调用对应的 left join / right join ... 连表方法否则会报错
* <p>
* 举例 UserDO AddressDO 为一对多关系 UserDTO 为结果类
* <pre>
* MPJLambdaWrapper&lt;UserDO&gt; wrapper = new MPJLambdaWrapper&lt;UserDO&gt;();
* wrapper.selectAll(UserDO.class)
* .selectCollection(AddressDO.class, UserDTO::getAddressListDTO)
* .leftJoin(AddressDO.class, ...... )
* .eq(...)
* ...
* <pre/>
* 会自动将 AddressDO类中相同属性的字段 以mybatis&lt;collection&gt;的方式映射到UserDTO.addressListDTO属性中
*
* @since 1.3.0
*
* @param child 连表数据库实体类
* @param dtoField 包装类对应的属性
* @param <S> 包装类
* @param <C> 对多数据库实体类
* @param <Z> 包装类集合泛型
* @param <F> 包装类集合字段泛型
*/
default <S, C, Z, F extends Collection<?>> Children selectCollection(BaseColumn<C> child, SFunction<S, F> dtoField) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<C, Z> builder;
if (genericType == null || genericType.isAssignableFrom(child.getColumnClass())) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType());
} else {
Class<Z> ofType = (Class<Z>) genericType;
builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), ofType, true);
}
addLabel(builder.build(), true);
return getChildren();
}
/**
* 一对多查询 调用此方法必需要调用对应的 left join / right join ... 连表方法否则会报错
* <p>
* 举例 UserDO AddressDO 为一对多关系 UserDTO 为结果类
* <pre>
* MPJLambdaWrapper&lt;UserDO&gt; wrapper = new MPJLambdaWrapper&lt;UserDO&gt;()
* .selectAll(UserDO.class)
* .selectCollection(AddressDO.class, UserDTO::getAddressListDTO, map -> map
* .id(AddressDO::getId, AddressDTO::getId) //如果属性名一致 可以传一个
* .result(AddressDO::getUserId) //如果属性名一致 可以传一个
* .result(AddressDO::getAddress, AddressDTO::getAddress)) //如果属性名一致 可以传一个
* .leftJoin(AddressDO.class, ...... )
* .eq(...)
* ...
* <pre/>
*
* 会自动将 AddressDO类中指定的字段 以mybatis&lt;collection&gt;的方式映射到UserDTO.addressListDTO属性中
*
* @since 1.3.0
*
* @param child 连表数据库实体类
* @param dtoField 包装类对应的属性
* @param collection collection标签内容
* @param <S> 包装类
* @param <C> 对多数据库实体类
* @param <Z> 包装类集合泛型
* @param <F> 包装类集合字段泛型
*/
default <S, C, Z, F extends Collection<Z>> Children selectCollection(BaseColumn<C> child,
SFunction<S, F> dtoField,
MFunction<MybatisLabel.Builder<C, Z>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<Z> ofType = (Class<Z>) genericType;
MybatisLabel.Builder<C, Z> builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), ofType, false);
MybatisLabel.Builder<C, Z> czBuilder = collection.apply(builder);
addLabel(czBuilder.build(), true);
return getChildren();
}
default <S, Z, F extends Collection<Z>> Children selectCollection(SFunction<S, F> dtoField,
MFunction<MybatisLabelFree.Builder<Z>> collection) {
//自由映射必须存在泛型Z
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<Z> ofType = (Class<Z>) genericType;
MybatisLabelFree.Builder<Z> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), ofType);
MybatisLabelFree.Builder<Z> czBuilder = collection.apply(builder);
addLabel(czBuilder.build(), true);
return getChildren();
}
/**
* 对一查询 用法参考 selectCollection
*
* @since 1.3.0
*/
default <S, C, F> Children selectAssociation(BaseColumn<C> child, SFunction<S, F> dtoField) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<C, F> builder;
builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), (Class<F>) field.getType(), true);
addLabel(builder.build(), false);
return getChildren();
}
default <S, C, F> Children selectAssociation(SFunction<S, F> dtoField,
MFunction<MybatisLabelFree.Builder<F>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabelFree.Builder<F> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), (Class<F>) field.getType());
MybatisLabelFree.Builder<F> cfBuilder = collection.apply(builder);
addLabel(cfBuilder.build(), false);
return getChildren();
}
default <S, C, F> Children selectAssociation(BaseColumn<C> child, SFunction<S, F> dtoField,
MFunction<MybatisLabel.Builder<C, F>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<S> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<C, F> builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), (Class<F>) field.getType(), false);
MybatisLabel.Builder<C, F> cfBuilder = collection.apply(builder);
addLabel(cfBuilder.build(), false);
return getChildren();
}
}

View File

@ -1,20 +0,0 @@
package com.github.yulichang.extension.apt.matedata;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author yulichang
* @since 1.5.0
*/
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class BaseColumn<T> implements Serializable {
protected String alias;
abstract public Class<T> getColumnClass();
}

View File

@ -1,31 +0,0 @@
package com.github.yulichang.extension.apt.matedata;
import lombok.Getter;
import java.io.Serializable;
import java.util.function.Supplier;
/**
* @author yulichang
* @since 1.5.0
*/
@Getter
public class Column implements Serializable {
private final BaseColumn<?> root;
private final String property;
public Column(BaseColumn<?> root, String property) {
this.root = root;
this.property = property;
}
public Class<?> getClazz() {
return root.getColumnClass();
}
public Supplier<String> getAlias() {
return root::getAlias;
}
}

View File

@ -1,275 +0,0 @@
package com.github.yulichang.extension.apt.resultmap;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.segments.SelectCache;
import lombok.Getter;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* collection 标签 目前先支持这几个属性 后续在扩展
*
* @author yulichang
* @since 1.3.0
*/
@Getter
public class MybatisLabel<E, T> implements Label<T> {
private String property;
private BaseColumn<E> baseColumn;
private Class<?> javaType;
private Class<T> ofType;
private List<IResult> resultList;
/**
* wrapper里面的引用
*/
private List<Label<?>> mybatisLabels;
private MybatisLabel() {
}
@SuppressWarnings({"unused", "unchecked", "DuplicatedCode"})
public static class Builder<E, T> {
private final MybatisLabel<E, T> mybatisLabel;
/**
* 自动构建
*/
public Builder(String property, BaseColumn<E> baseColumn, Class<?> javaType) {
this.mybatisLabel = new MybatisLabel<>();
mybatisLabel.property = property;
mybatisLabel.baseColumn = baseColumn;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = (Class<T>) baseColumn.getColumnClass();
mybatisLabel.resultList = new ArrayList<>();
mybatisLabel.mybatisLabels = new ArrayList<>();
autoBuild(true, baseColumn.getColumnClass(), (Class<T>) baseColumn.getColumnClass());
}
/**
* 手动构建
*
* @param property property
* @param baseColumn 数据库实体类
* @param javaType javaType
* @param ofType 映射类
* @param auto 自动映射数据库实体对应的字段
*/
public Builder(String property, BaseColumn<E> baseColumn, Class<?> javaType, Class<T> ofType, boolean auto) {
this.mybatisLabel = new MybatisLabel<>();
mybatisLabel.property = property;
mybatisLabel.baseColumn = baseColumn;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = ofType;
mybatisLabel.resultList = new ArrayList<>();
mybatisLabel.mybatisLabels = new ArrayList<>();
autoBuild(auto, baseColumn.getColumnClass(), ofType);
}
/**
* 映射实体全部字段
*/
public Builder<E, T> all() {
autoBuild(true, mybatisLabel.baseColumn.getColumnClass(), mybatisLabel.ofType);
return this;
}
/**
* 映射实体字段过滤(含主键)
*/
public Builder<E, T> filter(Predicate<SelectCache> predicate) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(mybatisLabel.ofType);
ColumnCache.getListField(mybatisLabel.baseColumn.getColumnClass()).stream().filter(predicate)
.filter(p -> fieldMap.containsKey(p.getColumProperty())).forEach(c ->
mybatisLabel.resultList.add(new Result.Builder<T>(c.isPk(), mybatisLabel.baseColumn, c).build()));
return this;
}
public Builder<E, T> id(Column column, SFunction<T, ?> tag) {
Result.Builder<T> builder = new Result.Builder<>(true, column);
builder.column(column).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> id(Column column) {
Result.Builder<T> builder = new Result.Builder<>(true, column);
builder.column(column);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> result(Column column, SFunction<T, ?> tag) {
Result.Builder<T> builder = new Result.Builder<>(false, column);
builder.column(column).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> result(Column column) {
Result.Builder<T> builder = new Result.Builder<>(false, column);
builder.column(column);
mybatisLabel.resultList.add(builder.build());
return this;
}
/**
* 嵌套
*/
public <A, R, B extends Collection<R>> Builder<E, T> collection(BaseColumn<A> entityClass, SFunction<T, B> func) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Builder<A, R> builder;
if (genericType == null || genericType.isAssignableFrom(entityClass.getColumnClass())) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new Builder<>(dtoFieldName, entityClass, field.getType());
} else {
Class<R> ofType = (Class<R>) genericType;
builder = new Builder<>(dtoFieldName, entityClass, field.getType(), ofType, true);
}
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
/**
* 嵌套
*/
public <A, R, B extends Collection<R>> Builder<E, T> collection(SFunction<T, B> func,
MFunction<MybatisLabelFree.Builder<R>> mFunc) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
MybatisLabelFree.Builder<R> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), ofType);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, R, B extends Collection<R>> Builder<E, T> collection(BaseColumn<A> entityClass,
SFunction<T, B> func,
MFunction<Builder<A, R>> mFunc) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
Builder<A, R> builder = new Builder<>(dtoFieldName, entityClass, field.getType(), ofType, false);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(BaseColumn<A> child, SFunction<T, B> dtoField) {
Class<T> dtoClass = LambdaUtils.getEntityClass(dtoField);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
String dtoFieldName = LambdaUtils.getName(dtoField);
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
Builder<A, B> builder;
builder = new Builder<>(dtoFieldName, child, field.getType(), (Class<B>) field.getType(), true);
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(SFunction<T, B> dtoField,
MFunction<MybatisLabelFree.Builder<B>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<T> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabelFree.Builder<B> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), (Class<B>) field.getType());
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(BaseColumn<A> child, SFunction<T, B> dtoField,
MFunction<Builder<A, B>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<T> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
Builder<A, B> builder = new Builder<>(dtoFieldName, child, field.getType(), (Class<B>) field.getType(), false);
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
public MybatisLabel<E, T> build() {
if (CollectionUtils.isEmpty(mybatisLabel.resultList)) {
autoBuild(true, mybatisLabel.baseColumn.getColumnClass(), mybatisLabel.ofType);
}
return mybatisLabel;
}
private void autoBuild(boolean auto, Class<E> entityClass, Class<T> tagClass) {
TableInfo tableInfo = TableHelper.getAssert(entityClass);
Map<String, FieldCache> tagMap = MPJReflectionKit.getFieldMap(tagClass);
if (auto && !tagMap.isEmpty()) {
List<SelectCache> listField = ColumnCache.getListField(entityClass);
if (entityClass.isAssignableFrom(tagClass)) {
mybatisLabel.resultList.addAll(listField.stream().map(i -> {
Result result = new Result();
result.setId(i.isPk());
result.setBaseColumn(mybatisLabel.baseColumn);
result.setProperty(i.getColumProperty());
result.setJavaType(i.getColumnType());
result.setJdbcType(i.getJdbcType());
result.setSelectNormal(i);
return result;
}).collect(Collectors.toList()));
} else {
for (SelectCache s : listField) {
FieldCache field = tagMap.get(s.getColumProperty());
if (Objects.nonNull(field)) {
Result result = new Result();
result.setId(s.isPk());
result.setBaseColumn(mybatisLabel.baseColumn);
result.setProperty(s.getColumProperty());
result.setJavaType(field.getType());
result.setSelectNormal(s);
mybatisLabel.resultList.add(result);
}
}
}
}
}
}
}

View File

@ -1,220 +0,0 @@
package com.github.yulichang.extension.apt.resultmap;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.resultmap.ResultList;
import com.github.yulichang.wrapper.segments.SelectCache;
import lombok.Getter;
import java.util.*;
import java.util.function.Predicate;
/**
* 无泛型约束 实现自由映射
*
* @author yulichang
* @since 1.4.4
*/
@Getter
public class MybatisLabelFree<T> implements Label<T> {
private String property;
private Class<?> javaType;
private Class<T> ofType;
private List<IResult> resultList;
/**
* wrapper里面的引用
*/
private List<Label<?>> mybatisLabels;
private MybatisLabelFree() {
}
@SuppressWarnings({"unused", "unchecked", "DuplicatedCode"})
public static class Builder<T> {
private final MybatisLabelFree<T> mybatisLabel;
/**
* 手动构建
*
* @param property property
* @param javaType javaType
* @param ofType 映射类
*/
public Builder(String property, Class<?> javaType, Class<T> ofType) {
this.mybatisLabel = new MybatisLabelFree<>();
mybatisLabel.property = property;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = ofType;
mybatisLabel.resultList = new ResultList();
mybatisLabel.mybatisLabels = new ArrayList<>();
}
public <E> Builder<T> all(BaseColumn<E> entityClass) {
allBuild(entityClass);
return this;
}
/**
* 映射实体字段过滤(含主键)
*/
public <E> Builder<T> filter(BaseColumn<E> baseColumn, Predicate<SelectCache> predicate) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(mybatisLabel.ofType);
ColumnCache.getListField(baseColumn.getColumnClass()).stream().filter(predicate)
.filter(p -> fieldMap.containsKey(p.getColumProperty())).forEach(c ->
mybatisLabel.resultList.add(new Result.Builder<T>(false, baseColumn, c).build()));
return this;
}
public Builder<T> id(Column column, SFunction<T, ?> tag) {
Result.Builder<T> builder = new Result.Builder<>(true, column);
builder.column(column).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> id(Column column) {
Result.Builder<T> builder = new Result.Builder<>(true, column);
builder.column(column);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(Column column, SFunction<T, ?> tag) {
Result.Builder<T> builder = new Result.Builder<>(false, column);
builder.column(column).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(Column column) {
Result.Builder<T> builder = new Result.Builder<>(false, column);
builder.column(column);
mybatisLabel.resultList.add(builder.build());
return this;
}
/**
* 嵌套
*/
public <A, R, B extends Collection<R>> Builder<T> collection(BaseColumn<A> baseColumn, SFunction<T, B> func) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<A, R> builder;
if (genericType == null || genericType.isAssignableFrom(baseColumn.getColumnClass())) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new MybatisLabel.Builder<>(dtoFieldName, baseColumn, field.getType());
} else {
Class<R> ofType = (Class<R>) genericType;
builder = new MybatisLabel.Builder<>(dtoFieldName, baseColumn, field.getType(), ofType, true);
}
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
public <A, R, B extends Collection<R>> Builder<T> collection(SFunction<T, B> func,
MFunction<Builder<R>> mFunc) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
Builder<R> builder = new Builder<>(dtoFieldName, field.getType(), ofType);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, R, B extends Collection<R>> Builder<T> collection(BaseColumn<A> entityClass,
SFunction<T, B> func,
MFunction<MybatisLabel.Builder<A, R>> mFunc) {
String dtoFieldName = LambdaUtils.getName(func);
Class<T> dtoClass = LambdaUtils.getEntityClass(func);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
MybatisLabel.Builder<A, R> builder = new MybatisLabel.Builder<>(dtoFieldName, entityClass, field.getType(), ofType, false);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<T> association(BaseColumn<A> child, SFunction<T, B> dtoField) {
Class<T> dtoClass = LambdaUtils.getEntityClass(dtoField);
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(dtoClass);
String dtoFieldName = LambdaUtils.getName(dtoField);
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<A, B> builder;
builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), (Class<B>) field.getType(), true);
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<T> association(BaseColumn<A> child, SFunction<T, B> dtoField,
MFunction<MybatisLabel.Builder<A, B>> collection) {
String dtoFieldName = LambdaUtils.getName(dtoField);
Class<T> dtoClass = LambdaUtils.getEntityClass(dtoField);
FieldCache field = MPJReflectionKit.getFieldMap(dtoClass).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<A, B> builder = new MybatisLabel.Builder<>(dtoFieldName, child, field.getType(), (Class<B>) field.getType(), false);
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
public MybatisLabelFree<T> build() {
if (CollectionUtils.isEmpty(mybatisLabel.resultList)) {
throw ExceptionUtils.mpe("无法自动映射, 找不到 <%s> 对应的表, 请使用 .all(xxx.class), id()或者result() 手动映射",
mybatisLabel.ofType.getSimpleName());
}
return mybatisLabel;
}
private void allBuild(BaseColumn<?> entityClass) {
Map<String, FieldCache> tagMap = MPJReflectionKit.getFieldMap(mybatisLabel.getOfType());
List<SelectCache> listField = ColumnCache.getListField(entityClass.getColumnClass());
for (SelectCache s : listField) {
FieldCache field = tagMap.get(s.getColumProperty());
if (Objects.nonNull(field)) {
Result result = new Result();
result.setBaseColumn(entityClass);
result.setId(s.isPk());
result.setJavaType(field.getType());
result.setProperty(s.getColumProperty());
result.setSelectNormal(s);
mybatisLabel.resultList.add(result);
}
}
}
}
}

View File

@ -1,123 +0,0 @@
package com.github.yulichang.extension.apt.resultmap;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.matedata.Column;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.segments.SelectCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.type.JdbcType;
import java.util.Map;
import java.util.Objects;
/**
* result 标签
*
* @author yulichang
* @since 1.3.0
*/
@Getter
@Setter(AccessLevel.PACKAGE)
public class Result implements IResult {
private boolean isId;
private BaseColumn<?> baseColumn;
private Column column;
private SelectCache selectNormal;
private String property;
private Class<?> javaType;
private JdbcType jdbcType;
public Result() {
}
@Override
public String getIndex() {
return null;
}
@SuppressWarnings({"UnusedReturnValue", "unused"})
public static class Builder<T> {
private final Result result;
public Builder(boolean isId, Column column) {
this.result = new Result();
result.isId = isId;
result.column = column;
result.baseColumn = column.getRoot();
}
public Builder(boolean isId, Column column, SelectCache selectCache) {
this.result = new Result();
result.isId = isId;
result.column = column;
result.baseColumn = column.getRoot();
result.selectNormal = selectCache;
result.property = selectCache.getColumProperty();
result.javaType = selectCache.getColumnType();
result.jdbcType = selectCache.getJdbcType();
}
public Builder(boolean isId, BaseColumn<?> baseColumn, SelectCache selectCache) {
this.result = new Result();
result.isId = isId;
result.column = null;
result.baseColumn = baseColumn;
result.selectNormal = selectCache;
result.property = selectCache.getColumProperty();
result.javaType = selectCache.getColumnType();
result.jdbcType = selectCache.getJdbcType();
}
public Builder<T> property(SFunction<T, ?> property) {
result.property = LambdaUtils.getName(property);
return this;
}
public Builder<T> column(Column column) {
Map<String, SelectCache> normalMap = ColumnCache.getMapField(column.getClazz());
SelectCache normal = normalMap.get(column.getProperty());
result.selectNormal = normal;
result.column = column;
if (StrUtils.isBlank(result.property)) {
result.property = normal.getColumProperty();
}
if (Objects.isNull(result.javaType)) {
result.javaType = normal.getColumnType();
}
if (Objects.isNull(result.jdbcType)) {
result.jdbcType = normal.getJdbcType();
}
return this;
}
public Builder<T> javaType(Class<?> javaType) {
result.javaType = javaType;
return this;
}
public Builder<T> jdbcType(JdbcType jdbcType) {
result.jdbcType = jdbcType;
return this;
}
public Result build() {
return result;
}
}
}

View File

@ -1,151 +0,0 @@
package com.github.yulichang.extension.apt.toolkit;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.extension.apt.AptQueryWrapper;
import com.github.yulichang.toolkit.LogicInfoUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.sql.SqlScriptUtils;
import java.util.Objects;
import java.util.Optional;
/**
* @author yulichang
* @since 1.4.5
*/
@SuppressWarnings("DuplicatedCode")
public class AptWrapperUtils {
public static <T> String buildSubSqlByWrapper(Class<T> clazz, AptQueryWrapper<T> wrapper, String alias) {
TableInfo tableInfo = TableHelper.getAssert(clazz);
String first = Optional.ofNullable(wrapper.getSqlFirst()).orElse(StringPool.EMPTY);
boolean hasWhere = false;
String entityWhere = getEntitySql(tableInfo, wrapper);
if (StrUtils.isNotBlank(entityWhere)) {
hasWhere = true;
}
String mainLogic = mainLogic(hasWhere, clazz, wrapper);
if (StrUtils.isNotBlank(mainLogic)) {
hasWhere = true;
}
String subLogic = subLogic(hasWhere, wrapper);
if (StrUtils.isNotBlank(subLogic)) {
hasWhere = true;
}
String sqlSegment = (wrapper.getSqlSegment() != null && StrUtils.isNotBlank(wrapper.getSqlSegment())) ?
((wrapper.isEmptyOfNormal() ? StringPool.EMPTY : (hasWhere ? " AND " : " WHERE ")) + wrapper.getSqlSegment()) : StringPool.EMPTY;
String sqlComment = Optional.ofNullable(wrapper.getSqlComment()).orElse(StringPool.EMPTY);
return String.format(" (%s SELECT %s FROM %s %s %s %s %s %s %s) AS %s ",
first,
wrapper.getSqlSelect(),
wrapper.getTableName(tableInfo.getTableName()),
wrapper.getAlias(),
wrapper.getFrom(),
mainLogic,
subLogic,
sqlSegment,
sqlComment,
alias);
}
public static String buildUnionSqlByWrapper(Class<?> clazz, AptQueryWrapper<?> wrapper) {
TableInfo tableInfo = TableHelper.getAssert(clazz);
String first = Optional.ofNullable(wrapper.getSqlFirst()).orElse(StringPool.EMPTY);
boolean hasWhere = false;
String entityWhere = getEntitySql(tableInfo, wrapper);
if (StrUtils.isNotBlank(entityWhere)) {
hasWhere = true;
}
String mainLogic = mainLogic(hasWhere, clazz, wrapper);
if (StrUtils.isNotBlank(mainLogic)) {
hasWhere = true;
}
String subLogic = subLogic(hasWhere, wrapper);
if (StrUtils.isNotBlank(subLogic)) {
hasWhere = true;
}
String sqlSegment = (wrapper.getSqlSegment() != null && StrUtils.isNotBlank(wrapper.getSqlSegment())) ?
((wrapper.isEmptyOfNormal() ? StringPool.EMPTY : (hasWhere ? " AND " : " WHERE ")) + wrapper.getSqlSegment()) : StringPool.EMPTY;
String sqlComment = Optional.ofNullable(wrapper.getSqlComment()).orElse(StringPool.EMPTY);
return String.format(" %s SELECT %s FROM %s %s %s %s %s %s %s ",
first,
wrapper.getSqlSelect(),
wrapper.getTableName(tableInfo.getTableName()),
wrapper.getAlias(),
wrapper.getFrom(),
mainLogic,
subLogic,
sqlSegment,
sqlComment);
}
private static <T> String formatParam(AptQueryWrapper<T> wrapper, Object param) {
final String genParamName = Constants.WRAPPER_PARAM + wrapper.getParamNameSeq().incrementAndGet();
final String paramStr = wrapper.getParamAlias() + ".paramNameValuePairs." + genParamName;
wrapper.getParamNameValuePairs().put(genParamName, param);
return SqlScriptUtils.safeParam(paramStr, null);
}
private static String getEntitySql(TableInfo tableInfo, AptQueryWrapper<?> wrapper) {
Object obj = wrapper.getEntity();
if (Objects.isNull(obj)) {
return StringPool.EMPTY;
}
StringBuilder sb = new StringBuilder(StringPool.EMPTY);
for (TableFieldInfo fieldInfo : tableInfo.getFieldList()) {
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo) && fieldInfo.isLogicDelete()) {
continue;
}
Object val;
try {
val = fieldInfo.getField().get(obj);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (Objects.isNull(val)) {
continue;
}
String s = wrapper.getAptIndex().get(wrapper.getBaseColumn());
sb.append(" AND ").append(s == null ? wrapper.getAlias() : s).append(Constants.DOT)
.append(fieldInfo.getColumn()).append(Constants.EQUALS).append(formatParam(wrapper, val));
}
//条件不为空 加上 where
if (sb.length() > 0) {
sb.delete(0, 4);
sb.insert(0, " WHERE ");
}
return sb.toString();
}
private static String mainLogic(boolean hasWhere, Class<?> clazz, AptQueryWrapper<?> wrapper) {
if (!wrapper.getLogicSql()) {
return StringPool.EMPTY;
}
String info = LogicInfoUtils.getLogicInfo(null, clazz, true, wrapper.getAlias());
if (StrUtils.isNotBlank(info)) {
if (hasWhere) {
return " AND " + info;
}
return " WHERE " + info.substring(4);
}
return StringPool.EMPTY;
}
private static String subLogic(boolean hasWhere, AptQueryWrapper<?> wrapper) {
String sql = wrapper.getSubLogicSql();
if (StrUtils.isNotBlank(sql)) {
if (hasWhere) {
return sql;
}
return " WHERE " + sql.substring(4);
}
return StringPool.EMPTY;
}
}

View File

@ -1,26 +0,0 @@
package com.github.yulichang.extension.apt.toolkit;
import com.github.yulichang.extension.apt.matedata.BaseColumn;
import com.github.yulichang.extension.apt.AptQueryWrapper;
/**
* @author yulichang
* @since 1.5.0
*/
@SuppressWarnings("unused")
public class AptWrappers {
/**
* AptWrappers.query(User.class)
*/
public static <T> AptQueryWrapper<T> query(BaseColumn<T> baseColumn) {
return new AptQueryWrapper<>(baseColumn);
}
/**
* AptWrappers.query("t", User.class)
*/
public static <T> AptQueryWrapper<T> query(BaseColumn<T> baseColumn, T entity) {
return new AptQueryWrapper<>(baseColumn, entity);
}
}

View File

@ -1,253 +0,0 @@
package com.github.yulichang.extension.kt;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.toolkit.LogicInfoUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.TableList;
import com.github.yulichang.wrapper.interfaces.DeleteChain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.4.5
*/
@SuppressWarnings({"unused", "DuplicatedCode"})
public class KtDeleteJoinWrapper<T> extends KtAbstractLambdaWrapper<T, KtDeleteJoinWrapper<T>> implements DeleteChain<T> {
/**
* 删除表
*/
private final SharedString deleteSql = new SharedString();
/**
* 删除的表
*/
private List<Class<?>> deleteTableList;
/**
* 删除的表
*/
private List<String> deleteTableName;
/**
* 是否删除主表以及所有副表
*/
private boolean deleteAll = false;
private KtDeleteJoinWrapper() {
super();
}
/**
* 推荐使用此构造方法
*/
public KtDeleteJoinWrapper(Class<T> clazz) {
super(clazz);
}
/**
* 构造方法
*
* @param clazz 主表class类
* @param alias 主表别名
*/
public KtDeleteJoinWrapper(Class<T> clazz, String alias) {
super(clazz, alias);
}
/**
* 获取删除的表
*/
@Override
public String getDeleteSql() {
if (StrUtils.isNotBlank(this.deleteSql.getStringValue())) {
return this.deleteSql.getStringValue();
}
String delete = null;
if (deleteAll) {
check();
List<String> tables = tableList.getAll().stream().map(i -> i.isHasAlias() ? i.getAlias() :
(i.getAlias() + i.getIndex())).collect(Collectors.toList());
tables.add(0, this.alias);
delete = String.join(StringPool.COMMA, tables);
} else {
if (CollectionUtils.isNotEmpty(deleteTableList)) {
delete = deleteTableList.stream().map(c -> tableList.getPrefixByClassAssert(c)).collect(Collectors.joining(StringPool.COMMA));
}
}
if (CollectionUtils.isNotEmpty(deleteTableName)) {
delete = delete + StringPool.COMMA + String.join(StringPool.COMMA, deleteTableName);
}
if (StrUtils.isBlank(delete)) {
delete = this.alias;
}
deleteSql.setStringValue(delete);
return delete;
}
/**
* 获取删除的表
*/
@Override
public String getDeleteLogicSql() {
if (StrUtils.isNotBlank(this.deleteSql.getStringValue())) {
return this.deleteSql.getStringValue();
}
String delete = null;
if (deleteAll) {
check();
delete = tableList.getAll().stream().map(i -> LogicInfoUtils.getLogicInfoInvert(i.getIndex(), i.getClazz(),
i.isHasAlias(), i.getAlias())).collect(Collectors.joining(StringPool.COMMA));
} else {
if (CollectionUtils.isNotEmpty(deleteTableList)) {
delete = deleteTableList.stream().map(c -> tableList.getByClassFirst(c)).map(i ->
LogicInfoUtils.getLogicInfoInvert(i.getIndex(), i.getClazz(), i.isHasAlias(), i.getAlias()))
.collect(Collectors.joining(StringPool.COMMA));
}
}
if (CollectionUtils.isNotEmpty(deleteTableName)) {
delete = delete + StringPool.COMMA + String.join(StringPool.COMMA, deleteTableName);
}
if (StrUtils.isNotBlank(delete)) {
delete = StringPool.COMMA + delete;
} else {
delete = StringPool.EMPTY;
}
deleteSql.setStringValue(delete);
return delete;
}
/**
* 删除表
*/
public KtDeleteJoinWrapper<T> deleteAll() {
this.deleteAll = true;
return typedThis;
}
/**
* 删除表
* 注意!!!
* 字符串不支持逻辑删除校验
* 也就算说此方法不管副表有没有逻辑删除 都按照主表的方式执行delete或update
*/
public KtDeleteJoinWrapper<T> delete(String... tables) {
if (CollectionUtils.isEmpty(deleteTableName)) {
deleteTableName = new ArrayList<>();
deleteTableName.addAll(Arrays.asList(tables));
}
return typedThis;
}
/**
* 删除表
*/
public KtDeleteJoinWrapper<T> delete(Class<?>... deleteClass) {
Class<T> entityClass = getEntityClass();
Assert.notNull(entityClass, "缺少主表类型, 请使用 new MPJLambdaWrapper<>(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
if (CollectionUtils.isEmpty(deleteTableList)) {
deleteTableList = new ArrayList<>();
}
check(Arrays.asList(deleteClass));
deleteTableList.addAll(Arrays.asList(deleteClass));
return typedThis;
}
private void check(List<Class<?>> classList) {
Class<T> entityClass = getEntityClass();
TableInfo tableInfo = TableHelper.getAssert(entityClass);
//检查
boolean mainLogic = AdapterHelper.getAdapter().mpjHasLogic(tableInfo);
boolean check = classList.stream().allMatch(t -> {
TableInfo ti = TableHelper.getAssert(t);
return mainLogic == AdapterHelper.getAdapter().mpjHasLogic(ti);
});
if (!check) {
throw ExceptionUtils.mpe("连表删除只适用于全部表(主表和副表)都是物理删除或全部都是逻辑删除, " +
"不支持同时存在物理删除和逻辑删除 [物理删除->(%s)] [逻辑删除->(%s)]",
classList.stream().filter(t -> !AdapterHelper.getAdapter().mpjHasLogic(TableHelper.getAssert(t)))
.map(Class::getSimpleName).collect(Collectors.joining(StringPool.COMMA)),
classList.stream().filter(t -> AdapterHelper.getAdapter().mpjHasLogic(TableHelper.getAssert(t)))
.map(Class::getSimpleName).collect(Collectors.joining(StringPool.COMMA)));
}
}
private void check() {
if (CollectionUtils.isNotEmpty(tableList.getAll())) {
Class<T> entityClass = getEntityClass();
Assert.notNull(entityClass, "缺少主表类型, 请使用 new MPJLambdaWrapper<>(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
ArrayList<Class<?>> list = tableList.getAll().stream().map(TableList.Node::getClazz)
.collect(Collectors.toCollection(ArrayList::new));
list.add(entityClass);
check(list);
}
}
/**
* 用于生成嵌套 sql
* <p> sqlSelect 不向下传递</p>
*/
@Override
protected KtDeleteJoinWrapper<T> instance() {
return instance(index, null, null, null);
}
@Override
protected KtDeleteJoinWrapper<T> instanceEmpty() {
return new KtDeleteJoinWrapper<>();
}
@Override
protected KtDeleteJoinWrapper<T> instance(Integer index, String keyWord, Class<?> joinClass, String tableName) {
return new KtDeleteJoinWrapper<>(getEntity(), getEntityClass(), paramNameSeq, paramNameValuePairs,
new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
this.tableList, index, keyWord, joinClass, tableName);
}
/**
* 不建议直接 new 该实例使用 JoinWrappers.delete(User.class)
*/
public KtDeleteJoinWrapper(T entity, Class<T> entityClass, AtomicInteger paramNameSeq,
Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
SharedString lastSql, SharedString sqlComment, SharedString sqlFirst,
TableList tableList, Integer index, String keyWord, Class<?> joinClass, String tableName) {
super.setEntity(entity);
super.setEntityClass(entityClass);
this.paramNameSeq = paramNameSeq;
this.paramNameValuePairs = paramNameValuePairs;
this.expression = mergeSegments;
this.lastSql = lastSql;
this.sqlComment = sqlComment;
this.sqlFirst = sqlFirst;
this.tableList = tableList;
this.index = index;
this.keyWord = keyWord;
this.joinClass = joinClass;
this.tableName = tableName;
}
@Override
public void clear() {
super.clear();
if (CollectionUtils.isNotEmpty(deleteTableList)) {
deleteTableList.clear();
}
if (CollectionUtils.isNotEmpty(deleteTableName)) {
deleteTableName.clear();
}
this.deleteSql.toNull();
this.deleteAll = false;
}
}

View File

@ -1,449 +0,0 @@
package com.github.yulichang.extension.kt;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.extension.kt.interfaces.Query;
import com.github.yulichang.extension.kt.interfaces.QueryLabel;
import com.github.yulichang.extension.kt.segments.FuncArgs;
import com.github.yulichang.extension.kt.toolkit.KtWrapperUtils;
import com.github.yulichang.extension.kt.toolkit.KtWrappers;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.TableList;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.interfaces.Chain;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.interfaces.SelectWrapper;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.segments.*;
import kotlin.reflect.KProperty;
import lombok.Getter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* 参考 {@link com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper}
* Lambda 语法使用 Wrapper
*
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings({"unused", "unchecked", "rawtypes", "DuplicatedCode"})
public class KtLambdaWrapper<T> extends KtAbstractLambdaWrapper<T, KtLambdaWrapper<T>> implements
Query<KtLambdaWrapper<T>>, QueryLabel<KtLambdaWrapper<T>>, Chain<T>, SelectWrapper<T, KtLambdaWrapper<T>> {
/**
* 查询字段 sql
*/
private SharedString sqlSelect = new SharedString();
/**
* 是否 select distinct
*/
private boolean selectDistinct = false;
/**
* 查询的字段
*/
@Getter
private final List<Select> selectColumns = new ArrayList<>();
/**
* 映射关系
*/
@Getter
private final List<Label<?>> resultMapMybatisLabel = new ArrayList<>();
/**
* union sql
*/
private SharedString unionSql;
/**
* 自定义wrapper索引
*/
private AtomicInteger wrapperIndex;
/**
* 自定义wrapper
*/
@Getter
private Map<String, Wrapper<?>> wrapperMap;
/**
* 推荐使用 class 的构造方法
*/
public KtLambdaWrapper() {
super();
}
/**
* 推荐使用此构造方法
*/
public KtLambdaWrapper(Class<T> clazz) {
super(clazz);
}
/**
* 构造方法
*
* @param entity 主表实体
*/
public KtLambdaWrapper(T entity) {
super(entity);
}
/**
* 自定义主表别名
*/
public KtLambdaWrapper(String alias) {
super(alias);
}
/**
* 构造方法
*
* @param clazz 主表class类
* @param alias 主表别名
*/
public KtLambdaWrapper(Class<T> clazz, String alias) {
super(clazz, alias);
}
/**
* 构造方法
*
* @param entity 主表实体类
* @param alias 主表别名
*/
public KtLambdaWrapper(T entity, String alias) {
super(entity, alias);
}
/**
* 不建议直接 new 该实例使用 JoinWrappers.lambda(UserDO.class)
*/
KtLambdaWrapper(T entity, Class<T> entityClass, SharedString sqlSelect, AtomicInteger paramNameSeq,
Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments, SharedString paramAlias,
SharedString lastSql, SharedString sqlComment, SharedString sqlFirst,
TableList tableList, Integer index, String keyWord, Class<?> joinClass, String tableName) {
super.setEntity(entity);
super.setEntityClass(entityClass);
this.paramNameSeq = paramNameSeq;
this.paramNameValuePairs = paramNameValuePairs;
this.expression = mergeSegments;
this.sqlSelect = sqlSelect;
this.paramAlias = paramAlias;
this.lastSql = lastSql;
this.sqlComment = sqlComment;
this.sqlFirst = sqlFirst;
this.tableList = tableList;
this.index = index;
this.keyWord = keyWord;
this.joinClass = joinClass;
this.tableName = tableName;
}
/**
* sql去重
* select distinct
*/
public KtLambdaWrapper<T> distinct() {
this.selectDistinct = true;
return typedThis;
}
@Override
public List<Select> getSelectColum() {
return this.selectColumns;
}
@Override
public void addLabel(Label<?> label, boolean isCollection) {
if (isCollection) {
this.resultMapCollection = true;
}
this.resultMap = true;
this.resultMapMybatisLabel.add(label);
}
@Override
public KtLambdaWrapper<T> getChildren() {
return typedThis;
}
/**
* 设置查询字段
*
* @param columns 字段数组
* @return children
*/
public final KtLambdaWrapper<T> select(KProperty<?>... columns) {
if (ArrayUtils.isNotEmpty(columns)) {
for (KProperty<?> s : columns) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(KtUtils.ref(s));
SelectCache cache = cacheMap.get(s.getName());
getSelectColum().add(new SelectNormal(cache, index, hasAlias, alias));
}
}
return typedThis;
}
@Override
public KtLambdaWrapper<T> selectAll() {
return Query.super.selectAll(getEntityClass());
}
/**
* 子查询
*/
public KtLambdaWrapper<T> selectSub(Class<?> clazz, Consumer<KtLambdaWrapper<?>> consumer, KProperty<?> alias) {
return selectSub(clazz, ConfigProperties.subQueryAlias, consumer, alias);
}
public <E, F> KtLambdaWrapper<T> selectSub(Class<E> clazz, String st, Consumer<KtLambdaWrapper<?>> consumer, KProperty<?> alias) {
return selectSub(clazz, st, consumer, alias.getName());
}
/**
* 子查询
*/
public KtLambdaWrapper<T> selectSub(Class<?> clazz, String st,
Consumer<KtLambdaWrapper<?>> consumer, String alias) {
KtLambdaWrapper<?> wrapper = new KtLambdaWrapper(null, clazz, SharedString.emptyString(), paramNameSeq,
paramNameValuePairs, new MergeSegments(), new SharedString(this.paramAlias.getStringValue()),
SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(), new TableList(),
null, null, null, null) {
};
wrapper.tableList.setAlias(st);
wrapper.tableList.setRootClass(clazz);
wrapper.tableList.setParent(this.tableList);
wrapper.alias = st;
wrapper.subTableAlias = st;
consumer.accept(wrapper);
addCustomWrapper(wrapper);
this.selectColumns.add(new SelectSub(() -> KtWrapperUtils.buildSubSqlByWrapper(
clazz, wrapper, alias), hasAlias, this.alias, alias));
return typedThis;
}
@Override
public KtLambdaWrapper<T> selectFunc(String sql, MFunction<FuncArgs> column, String alias) {
FuncArgs apply = column.apply(new FuncArgs());
String formatSql;
if (ArrayUtils.isEmpty(apply.getValues())) {
formatSql = sql;
} else {
formatSql = formatSqlMaybeWithParam(sql, apply.getValues());
}
getSelectColum().add(new SelectFunc(alias, getIndex(), () -> formatSql, apply.getFuncArg(),
isHasAlias(), getAlias()));
return typedThis;
}
/**
* union
* <p>
* 推荐使用 union(Class&lt;U&gt; clazz, Consumer&lt;MPJLambdaWrapper&lt;U&gt;&gt; consumer)
* wrapper.union(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @see #union(Class, Consumer)
* @deprecated union 不支持子查询
*/
@Deprecated
@SuppressWarnings("ALL")
public final KtLambdaWrapper<T> union(KtLambdaWrapper<?>... wrappers) {
StringBuilder sb = new StringBuilder();
for (KtLambdaWrapper<?> wrapper : wrappers) {
addCustomWrapper(wrapper);
Class<?> entityClass = wrapper.getEntityClass();
Assert.notNull(entityClass, "请使用 new MPJLambdaWrapper(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
sb.append(" UNION ").append(KtWrapperUtils.buildUnionSqlByWrapper(entityClass, wrapper));
}
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
/**
* union
* <p>
* wrapper.union(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @param clazz union语句的主表类型
* @since 1.4.8
*/
public <U> KtLambdaWrapper<T> union(Class<U> clazz, Consumer<KtLambdaWrapper<U>> consumer) {
KtLambdaWrapper<U> unionWrapper = KtWrappers.query(clazz);
addCustomWrapper(unionWrapper);
consumer.accept(unionWrapper);
String sb = " UNION " + KtWrapperUtils.buildUnionSqlByWrapper(clazz, unionWrapper);
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
/**
* union
* <p>
* 推荐使用 unionAll(Class&lt;U&gt; clazz, Consumer&lt;MPJLambdaWrapper&lt;U&gt;&gt; consumer)
* wrapper.unionAll(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @see #unionAll(Class, Consumer)
* @deprecated union 不支持子查询
*/
@Deprecated
@SuppressWarnings("ALL")
public final KtLambdaWrapper<T> unionAll(KtLambdaWrapper<?>... wrappers) {
StringBuilder sb = new StringBuilder();
for (KtLambdaWrapper<?> wrapper : wrappers) {
addCustomWrapper(wrapper);
Class<?> entityClass = wrapper.getEntityClass();
Assert.notNull(entityClass, "请使用 new MPJLambdaWrapper(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
sb.append(" UNION ALL ").append(KtWrapperUtils.buildUnionSqlByWrapper(entityClass, wrapper));
}
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
/**
* union
* <p>
* wrapper.unionAll(UserDO.class, union -> union.selectAll(UserDO.class))
*
* @param clazz union语句的主表类型
* @since 1.4.8
*/
public <U> KtLambdaWrapper<T> unionAll(Class<U> clazz, Consumer<KtLambdaWrapper<U>> consumer) {
KtLambdaWrapper<U> unionWrapper = KtWrappers.query(clazz);
addCustomWrapper(unionWrapper);
consumer.accept(unionWrapper);
String sb = " UNION ALL " + KtWrapperUtils.buildUnionSqlByWrapper(clazz, unionWrapper);
if (Objects.isNull(unionSql)) {
unionSql = SharedString.emptyString();
}
unionSql.setStringValue(unionSql.getStringValue() + sb);
return typedThis;
}
private void addCustomWrapper(KtLambdaWrapper<?> wrapper) {
if (Objects.isNull(wrapperIndex)) {
wrapperIndex = new AtomicInteger(0);
}
int index = wrapperIndex.incrementAndGet();
if (Objects.isNull(wrapperMap)) {
wrapperMap = new HashMap<>();
}
String key = "ew" + index;
wrapper.setParamAlias(wrapper.getParamAlias() + ".wrapperMap." + key);
wrapperMap.put(key, wrapper);
}
/**
* 查询条件 SQL 片段
*/
@Override
public String getSqlSelect() {
if (StrUtils.isBlank(sqlSelect.getStringValue()) && CollectionUtils.isNotEmpty(selectColumns)) {
String s = selectColumns.stream().map(i -> {
if (i.isStr()) {
return i.getColumn();
}
String prefix;
if (i.isHasTableAlias()) {
prefix = i.getTableAlias();
} else {
if (i.isLabel()) {
if (i.isHasTableAlias()) {
prefix = i.getTableAlias();
} else {
prefix = tableList.getPrefix(i.getIndex(), i.getClazz(), true);
}
} else {
prefix = tableList.getPrefix(i.getIndex(), i.getClazz(), false);
}
}
String str = prefix + StringPool.DOT + i.getColumn();
if (i.isFunc()) {
SelectFunc.Arg[] args = i.getArgs();
if (Objects.isNull(args) || args.length == 0) {
return String.format(i.getFunc().getSql(), str) + Constant.AS + i.getAlias();
} else {
return String.format(i.getFunc().getSql(), Arrays.stream(args).map(arg -> {
String prefixByClass = tableList.getPrefixByClass(arg.getClazz());
Map<String, SelectCache> mapField = ColumnCache.getMapField(arg.getClazz());
SelectCache cache = mapField.get(arg.getProp());
return prefixByClass + StringPool.DOT + cache.getColumn();
}).toArray()) + Constant.AS + i.getAlias();
}
} else {
return i.isHasAlias() ? (str + Constant.AS + i.getAlias()) : str;
}
}).collect(Collectors.joining(StringPool.COMMA));
sqlSelect.setStringValue(s);
}
return sqlSelect.getStringValue();
}
@Override
public String getUnionSql() {
return Optional.ofNullable(unionSql).map(SharedString::getStringValue).orElse(StringPool.EMPTY);
}
public boolean getSelectDistinct() {
return selectDistinct;
}
/**
* 用于生成嵌套 sql
* <p> sqlSelect 不向下传递</p>
*/
@Override
protected KtLambdaWrapper<T> instance() {
return instance(index, null, null, null);
}
@Override
protected KtLambdaWrapper<T> instanceEmpty() {
return new KtLambdaWrapper<>();
}
@Override
protected KtLambdaWrapper<T> instance(Integer index, String keyWord, Class<?> joinClass, String tableName) {
return new KtLambdaWrapper<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs,
new MergeSegments(), this.paramAlias, SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
this.tableList, index, keyWord, joinClass, tableName);
}
@Override
public void clear() {
super.clear();
selectDistinct = false;
sqlSelect.toEmpty();
if (Objects.nonNull(unionSql)) unionSql.toEmpty();
selectColumns.clear();
wrapperIndex = new AtomicInteger(0);
wrapperMap.clear();
resultMapMybatisLabel.clear();
}
}

View File

@ -1,287 +0,0 @@
package com.github.yulichang.extension.kt;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.extension.kt.interfaces.Update;
import com.github.yulichang.toolkit.*;
import com.github.yulichang.toolkit.ReflectionKit;
import com.github.yulichang.wrapper.interfaces.UpdateChain;
import kotlin.reflect.KProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings({"unused", "DuplicatedCode"})
public class KtUpdateJoinWrapper<T> extends KtAbstractLambdaWrapper<T, KtUpdateJoinWrapper<T>>
implements Update<KtUpdateJoinWrapper<T>>, UpdateChain<T> {
/**
* SQL 更新字段内容例如name='1', age=2
*/
private final SharedString sqlSetStr = new SharedString();
/**
* SQL 更新字段内容例如name='1', age=2
*/
private List<String> sqlSet;
/**
* SQL 更新字段内容例如name='1', age=2
*/
private List<UpdateSet> updateSet;
/**
* SQL 更新实体(更新非空字段)
*/
private List<Object> updateEntity;
/**
* SQL 更新实体(空字段也会更新)
*/
private List<Object> updateEntityNull;
private KtUpdateJoinWrapper() {
super();
}
/**
* 推荐使用此构造方法
*/
public KtUpdateJoinWrapper(Class<T> clazz) {
super(clazz);
}
public KtUpdateJoinWrapper(T entity) {
super(entity);
}
public KtUpdateJoinWrapper(Class<T> clazz, String alias) {
super(clazz, alias);
}
public KtUpdateJoinWrapper(T entity, String alias) {
super(entity, alias);
}
/**
* 设置更新的实体set语句部分, 更新非空字段
* <p>
* 注意!!!
* 这里这是的实体类是set部分, 不作为条件, where条件是wrapper.setEntity()
*/
public KtUpdateJoinWrapper<T> setUpdateEntity(Object... entity) {
if (Objects.isNull(updateEntity)) {
updateEntity = new ArrayList<>();
}
for (Object obj : entity) {
Assert.notNull(obj, "更新实体不能为空");
updateEntity.add(obj);
}
return typedThis;
}
/**
* 设置更新的实体set语句部分, 更新非空字段
* <p>
* 注意!!!
* 这里这是的实体类是set部分, 不作为条件, where条件是wrapper.setEntity()
*/
public KtUpdateJoinWrapper<T> setUpdateEntityAndNull(Object... entity) {
if (Objects.isNull(updateEntityNull)) {
updateEntityNull = new ArrayList<>();
}
for (Object obj : entity) {
Assert.notNull(obj, "更新实体不能为空");
updateEntityNull.add(obj);
}
return typedThis;
}
@Override
public KtUpdateJoinWrapper<T> set(boolean condition, KProperty<?> column, Object val, String mapping) {
return maybeDo(condition, () -> {
if (Objects.isNull(updateSet)) {
updateSet = new ArrayList<>();
}
updateSet.add(new UpdateSet(column, val, mapping, false, null));
});
}
@Override
public KtUpdateJoinWrapper<T> setIncrBy(boolean condition, KProperty<?> column, Number val) {
return maybeDo(condition, () -> {
if (Objects.isNull(updateSet)) {
updateSet = new ArrayList<>();
}
updateSet.add(new UpdateSet(column, val, null, true, Constant.PLUS));
});
}
@Override
public KtUpdateJoinWrapper<T> setDecrBy(boolean condition, KProperty<?> column, Number val) {
return maybeDo(condition, () -> {
if (Objects.isNull(updateSet)) {
updateSet = new ArrayList<>();
}
updateSet.add(new UpdateSet(column, val, null, true, Constant.DASH));
});
}
@Override
public KtUpdateJoinWrapper<T> setSql(boolean condition, String sql) {
if (condition && StrUtils.isNotBlank(sql)) {
if (Objects.isNull(sqlSet)) {
sqlSet = new ArrayList<>();
}
sqlSet.add(sql);
}
return typedThis;
}
@Override
public String getSqlSet() {
if (StrUtils.isNotBlank(sqlSetStr.getStringValue())) {
return sqlSetStr.getStringValue();
}
StringBuilder set = new StringBuilder(StringPool.EMPTY);
if (CollectionUtils.isNotEmpty(updateSet)) {
set = new StringBuilder(updateSet.stream().map(i -> {
String col = tableList.getPrefixByClass(KtUtils.ref(i.getColumn())) +
Constants.DOT + getCache(i.getColumn()).getColumn();
if (i.incOrDnc) {
return col + Constants.EQUALS + col + i.cal + i.value;
} else {
return col + Constants.EQUALS + formatParam(i.mapping, i.value);
}
})
.collect(Collectors.joining(StringPool.COMMA)) + StringPool.COMMA);
}
if (CollectionUtils.isNotEmpty(sqlSet)) {
set.append(String.join(StringPool.COMMA, sqlSet)).append(StringPool.COMMA);
}
if (CollectionUtils.isNotEmpty(updateEntity)) {
getSqlByEntity(set, true, updateEntity);
}
if (CollectionUtils.isNotEmpty(updateEntityNull)) {
getSqlByEntity(set, false, updateEntityNull);
}
sqlSetStr.setStringValue(set.toString());
return set.toString();
}
/**
* 用于生成嵌套 sql
* <p> sqlSelect 不向下传递</p>
*/
@Override
protected KtUpdateJoinWrapper<T> instance() {
return instance(index, null, null, null);
}
@Override
protected KtUpdateJoinWrapper<T> instanceEmpty() {
return new KtUpdateJoinWrapper<>();
}
@Override
protected KtUpdateJoinWrapper<T> instance(Integer index, String keyWord, Class<?> joinClass, String tableName) {
return new KtUpdateJoinWrapper<>(getEntity(), getEntityClass(), paramNameSeq, paramNameValuePairs,
new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
this.tableList, index, keyWord, joinClass, tableName);
}
/**
* 不建议直接 new 该实例使用 JoinWrappers.update(User.class)
*/
public KtUpdateJoinWrapper(T entity, Class<T> entityClass, AtomicInteger paramNameSeq,
Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
SharedString lastSql, SharedString sqlComment, SharedString sqlFirst,
TableList tableList, Integer index, String keyWord, Class<?> joinClass, String tableName) {
super.setEntity(entity);
super.setEntityClass(entityClass);
this.paramNameSeq = paramNameSeq;
this.paramNameValuePairs = paramNameValuePairs;
this.expression = mergeSegments;
this.lastSql = lastSql;
this.sqlComment = sqlComment;
this.sqlFirst = sqlFirst;
this.tableList = tableList;
this.index = index;
this.keyWord = keyWord;
this.joinClass = joinClass;
this.tableName = tableName;
}
private void getSqlByEntity(StringBuilder sb, boolean filterNull, List<Object> entityList) {
for (Object obj : entityList) {
Assert.isTrue(tableList.contain(obj.getClass()), "更新的实体不是主表或关联表 <%>", obj.getClass().getSimpleName());
TableInfo tableInfo = TableHelper.getAssert(obj.getClass());
for (TableFieldInfo fieldInfo : tableInfo.getFieldList()) {
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo) && fieldInfo.isLogicDelete()) {
continue;
}
Object val;
try {
Field field = AdapterHelper.getAdapter().mpjGetField(fieldInfo, () -> {
Field field1 = ReflectionKit.getFieldMap(obj.getClass()).get(fieldInfo.getProperty());
field1.setAccessible(true);
return field1;
});
val = field.get(obj);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (filterNull && Objects.isNull(val)) {
continue;
}
sb.append(tableList.getPrefixByClass(obj.getClass())).append(Constants.DOT)
.append(fieldInfo.getColumn()).append(Constants.EQUALS).append(formatParam(null, val))
.append(StringPool.COMMA);
}
}
}
@Override
public void clear() {
super.clear();
sqlSetStr.toNull();
if (CollectionUtils.isNotEmpty(sqlSet)) {
sqlSet.clear();
}
if (CollectionUtils.isNotEmpty(updateSet)) {
updateSet.clear();
}
if (CollectionUtils.isNotEmpty(updateEntity)) {
updateEntity.clear();
}
if (CollectionUtils.isNotEmpty(updateEntityNull)) {
updateEntityNull.clear();
}
}
@Data
@AllArgsConstructor
public static class UpdateSet {
private KProperty<?> column;
private Object value;
private String mapping;
private boolean incOrDnc;
private String cal;
}
}

View File

@ -1,360 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import kotlin.reflect.KProperty;
import java.io.Serializable;
import java.util.Map;
/**
* 将原来的泛型R改成KProperty<?>
* <p>
* {@link com.baomidou.mybatisplus.core.conditions.interfaces.Compare}
*/
@SuppressWarnings("unused")
public interface Compare<Children> extends Serializable {
default Children allEq(Map<KProperty<?>, ?> params) {
return allEq(params, true);
}
default Children allEq(Map<KProperty<?>, ?> params, boolean null2IsNull) {
return allEq(true, params, null2IsNull);
}
/**
* map 所有非空属性等于 =
*
* @param condition 执行条件
* @param params map 类型的参数, key 是字段名, value 是字段值
* @param null2IsNull 是否参数为 null 自动执行 isNull 方法, false 则忽略这个字段\
* @return children
*/
Children allEq(boolean condition, Map<KProperty<?>, ?> params, boolean null2IsNull);
default Children eq(KProperty<?> column, Object val) {
return eq(true, null, column, val);
}
default Children eq(String alias, KProperty<?> column, Object val) {
return eq(true, alias, column, val);
}
default Children eq(boolean condition, KProperty<?> column, Object val) {
return eq(condition, null, column, val);
}
/**
* 等于 =
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children eq(boolean condition, String alias, KProperty<?> column, Object val);
default Children ne(KProperty<?> column, Object val) {
return ne(true, null, column, val);
}
default Children ne(String alias, KProperty<?> column, Object val) {
return ne(true, alias, column, val);
}
default Children ne(boolean condition, KProperty<?> column, Object val) {
return ne(condition, null, column, val);
}
/**
* 不等于 &lt;&gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ne(boolean condition, String alias, KProperty<?> column, Object val);
default Children gt(KProperty<?> column, Object val) {
return gt(true, null, column, val);
}
default Children gt(String alias, KProperty<?> column, Object val) {
return gt(true, alias, column, val);
}
default Children gt(boolean condition, KProperty<?> column, Object val) {
return gt(condition, null, column, val);
}
/**
* 大于 &gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children gt(boolean condition, String alias, KProperty<?> column, Object val);
default Children ge(KProperty<?> column, Object val) {
return ge(true, null, column, val);
}
default Children ge(String alias, KProperty<?> column, Object val) {
return ge(true, alias, column, val);
}
default Children ge(boolean condition, KProperty<?> column, Object val) {
return ge(condition, null, column, val);
}
/**
* 大于等于 &gt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ge(boolean condition, String alias, KProperty<?> column, Object val);
default Children lt(KProperty<?> column, Object val) {
return lt(true, null, column, val);
}
default Children lt(String alias, KProperty<?> column, Object val) {
return lt(true, alias, column, val);
}
default Children lt(boolean condition, KProperty<?> column, Object val) {
return lt(condition, null, column, val);
}
/**
* 小于 &lt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children lt(boolean condition, String alias, KProperty<?> column, Object val);
default Children le(KProperty<?> column, Object val) {
return le(true, null, column, val);
}
default Children le(String alias, KProperty<?> column, Object val) {
return le(true, alias, column, val);
}
default Children le(boolean condition, KProperty<?> column, Object val) {
return le(condition, null, column, val);
}
/**
* 小于等于 &lt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children le(boolean condition, String alias, KProperty<?> column, Object val);
default Children between(KProperty<?> column, Object val1, Object val2) {
return between(true, null, column, val1, val2);
}
default Children between(String alias, KProperty<?> column, Object val1, Object val2) {
return between(true, alias, column, val1, val2);
}
default Children between(boolean condition, KProperty<?> column, Object val1, Object val2) {
return between(condition, null, column, val1, val2);
}
/**
* BETWEEN 值1 AND 值2
*
* @param condition 执行条件
* @param column 字段
* @param val1 值1
* @param val2 值2
* @return children
*/
Children between(boolean condition, String alias, KProperty<?> column, Object val1, Object val2);
default Children notBetween(KProperty<?> column, Object val1, Object val2) {
return notBetween(true, null, column, val1, val2);
}
default Children notBetween(String alias, KProperty<?> column, Object val1, Object val2) {
return notBetween(true, alias, column, val1, val2);
}
default Children notBetween(boolean condition, KProperty<?> column, Object val1, Object val2) {
return notBetween(condition, null, column, val1, val2);
}
/**
* NOT BETWEEN 值1 AND 值2
*
* @param condition 执行条件
* @param column 字段
* @param val1 值1
* @param val2 值2
* @return children
*/
Children notBetween(boolean condition, String alias, KProperty<?> column, Object val1, Object val2);
default Children like(KProperty<?> column, Object val) {
return like(true, null, column, val);
}
default Children like(String alisa, KProperty<?> column, Object val) {
return like(true, alisa, column, val);
}
default Children like(boolean condition, KProperty<?> column, Object val) {
return like(condition, null, column, val);
}
/**
* LIKE '%%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children like(boolean condition, String alias, KProperty<?> column, Object val);
default Children notLike(KProperty<?> column, Object val) {
return notLike(true, null, column, val);
}
default Children notLike(String alias, KProperty<?> column, Object val) {
return notLike(true, alias, column, val);
}
default Children notLike(boolean condition, KProperty<?> column, Object val) {
return notLike(condition, null, column, val);
}
/**
* NOT LIKE '%%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children notLike(boolean condition, String alias, KProperty<?> column, Object val);
default Children likeLeft(KProperty<?> column, Object val) {
return likeLeft(true, null, column, val);
}
default Children likeLeft(String alias, KProperty<?> column, Object val) {
return likeLeft(true, alias, column, val);
}
default Children likeLeft(boolean condition, KProperty<?> column, Object val) {
return likeLeft(condition, null, column, val);
}
/**
* LIKE '%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children likeLeft(boolean condition, String alias, KProperty<?> column, Object val);
default Children notLikeLeft(KProperty<?> column, Object val) {
return notLikeLeft(true, null, column, val);
}
default Children notLikeLeft(String alias, KProperty<?> column, Object val) {
return notLikeLeft(true, alias, column, val);
}
default Children notLikeLeft(boolean condition, KProperty<?> column, Object val) {
return notLikeLeft(condition, null, column, val);
}
/**
* LIKE '%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children notLikeLeft(boolean condition, String alias, KProperty<?> column, Object val);
default Children likeRight(KProperty<?> column, Object val) {
return likeRight(true, null, column, val);
}
default Children likeRight(String alias, KProperty<?> column, Object val) {
return likeRight(true, alias, column, val);
}
default Children likeRight(boolean condition, KProperty<?> column, Object val) {
return likeRight(condition, null, column, val);
}
/**
* LIKE '%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children likeRight(boolean condition, String alias, KProperty<?> column, Object val);
default Children notLikeRight(KProperty<?> column, Object val) {
return notLikeRight(true, null, column, val);
}
default Children notLikeRight(String alias, KProperty<?> column, Object val) {
return notLikeRight(true, alias, column, val);
}
default Children notLikeRight(boolean condition, KProperty<?> column, Object val) {
return notLikeRight(condition, null, column, val);
}
/**
* LIKE '%'
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children notLikeRight(boolean condition, String alias, KProperty<?> column, Object val);
}

View File

@ -1,115 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import com.github.yulichang.wrapper.enums.IfExistsSqlKeyWordEnum;
import kotlin.reflect.KProperty;
import java.util.function.BiPredicate;
/**
* IfExists
*
* @author yulichang
* @since 1.4.9
*/
@SuppressWarnings("unused")
public interface CompareIfExists<Children> extends Compare<Children> {
BiPredicate<Object, IfExistsSqlKeyWordEnum> getIfExists();
default Children eqIfExists(KProperty<?> column, Object val) {
return eq(getIfExists().test(val, IfExistsSqlKeyWordEnum.EQ), null, column, val);
}
default Children eqIfExists(String alias, KProperty<?> column, Object val) {
return eq(getIfExists().test(val, IfExistsSqlKeyWordEnum.EQ), alias, column, val);
}
default Children neIfExists(KProperty<?> column, Object val) {
return ne(getIfExists().test(val, IfExistsSqlKeyWordEnum.NE), null, column, val);
}
default Children neIfExists(String alias, KProperty<?> column, Object val) {
return ne(getIfExists().test(val, IfExistsSqlKeyWordEnum.NE), alias, column, val);
}
default Children gtIfExists(KProperty<?> column, Object val) {
return gt(getIfExists().test(val, IfExistsSqlKeyWordEnum.GT), null, column, val);
}
default Children gtIfExists(String alias, KProperty<?> column, Object val) {
return gt(getIfExists().test(val, IfExistsSqlKeyWordEnum.GT), alias, column, val);
}
default Children geIfExists(KProperty<?> column, Object val) {
return ge(getIfExists().test(val, IfExistsSqlKeyWordEnum.GE), null, column, val);
}
default Children geIfExists(String alias, KProperty<?> column, Object val) {
return ge(getIfExists().test(val, IfExistsSqlKeyWordEnum.GE), alias, column, val);
}
default Children ltIfExists(KProperty<?> column, Object val) {
return lt(getIfExists().test(val, IfExistsSqlKeyWordEnum.LT), null, column, val);
}
default Children ltIfExists(String alias, KProperty<?> column, Object val) {
return lt(getIfExists().test(val, IfExistsSqlKeyWordEnum.LT), alias, column, val);
}
default Children leIfExists(KProperty<?> column, Object val) {
return le(getIfExists().test(val, IfExistsSqlKeyWordEnum.LE), null, column, val);
}
default Children leIfExists(String alias, KProperty<?> column, Object val) {
return le(getIfExists().test(val, IfExistsSqlKeyWordEnum.LE), alias, column, val);
}
default Children likeIfExists(KProperty<?> column, Object val) {
return like(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE), null, column, val);
}
default Children likeIfExists(String alisa, KProperty<?> column, Object val) {
return like(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE), alisa, column, val);
}
default Children notLikeIfExists(KProperty<?> column, Object val) {
return notLike(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE), null, column, val);
}
default Children notLikeIfExists(String alias, KProperty<?> column, Object val) {
return notLike(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE), alias, column, val);
}
default Children likeLeftIfExists(KProperty<?> column, Object val) {
return likeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_LEFT), null, column, val);
}
default Children likeLeftIfExists(String alias, KProperty<?> column, Object val) {
return likeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_LEFT), alias, column, val);
}
default Children notLikeLeftIfExists(KProperty<?> column, Object val) {
return notLikeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_LEFT), null, column, val);
}
default Children notLikeLeftIfExists(String alias, KProperty<?> column, Object val) {
return notLikeLeft(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_LEFT), alias, column, val);
}
default Children likeRightIfExists(KProperty<?> column, Object val) {
return likeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_RIGHT), null, column, val);
}
default Children likeRightIfExists(String alias, KProperty<?> column, Object val) {
return likeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.LIKE_RIGHT), alias, column, val);
}
default Children notLikeRightIfExists(KProperty<?> column, Object val) {
return notLikeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_RIGHT), null, column, val);
}
default Children notLikeRightIfExists(String alias, KProperty<?> column, Object val) {
return notLikeRight(getIfExists().test(val, IfExistsSqlKeyWordEnum.NOT_LIKE_RIGHT), alias, column, val);
}
}

View File

@ -1,491 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import kotlin.reflect.KProperty;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
/**
* 将原来的泛型R改成KProperty<?>
* <p>
* copy {@link com.baomidou.mybatisplus.core.conditions.interfaces.Func}
*/
@SuppressWarnings("unused")
public interface Func<Children> extends Serializable {
default Children isNull(KProperty<?> column) {
return isNull(true, null, column);
}
default Children isNull(String alias, KProperty<?> column) {
return isNull(true, alias, column);
}
default Children isNull(boolean condition, KProperty<?> column) {
return isNull(condition, null, column);
}
/**
* 字段 IS NULL
* <p>: isNull("name")</p>
*
* @param condition 执行条件
* @param column 字段
* @return children
*/
Children isNull(boolean condition, String alias, KProperty<?> column);
default Children isNotNull(KProperty<?> column) {
return isNotNull(true, null, column);
}
default Children isNotNull(String alias, KProperty<?> column) {
return isNotNull(true, alias, column);
}
default Children isNotNull(boolean condition, KProperty<?> column) {
return isNotNull(condition, null, column);
}
/**
* 字段 IS NOT NULL
* <p>: isNotNull("name")</p>
*
* @param condition 执行条件
* @param column 字段
* @return children
*/
Children isNotNull(boolean condition, String alias, KProperty<?> column);
default Children in(KProperty<?> column, Collection<?> coll) {
return in(true, null, column, coll);
}
default Children in(String alias, KProperty<?> column, Collection<?> coll) {
return in(true, alias, column, coll);
}
default Children in(boolean condition, KProperty<?> column, Collection<?> coll) {
return in(condition, null, column, coll);
}
/**
* 字段 IN (value.get(0), value.get(1), ...)
* <p>: in("id", Arrays.asList(1, 2, 3, 4, 5))</p>
*
* <li> 注意集合为空若存在逻辑错误请在 condition 条件中判断 </li>
* <li> 如果集合为 empty 则不会进行 sql 拼接 </li>
*
* @param condition 执行条件
* @param column 字段
* @param coll 数据集合
* @return children
*/
Children in(boolean condition, String alias, KProperty<?> column, Collection<?> coll);
default Children in(KProperty<?> column, Object... values) {
return in(true, null, column, values);
}
default Children in(String alias, KProperty<?> column, Object... values) {
return in(true, alias, column, values);
}
default Children in(boolean condition, KProperty<?> column, Object... values) {
return in(condition, null, column, values);
}
/**
* 字段 IN (v0, v1, ...)
* <p>: in("id", 1, 2, 3, 4, 5)</p>
*
* <li> 注意数组为空若存在逻辑错误请在 condition 条件中判断 </li>
* <li> 如果动态数组为 empty 则不会进行 sql 拼接 </li>
*
* @param condition 执行条件
* @param column 字段
* @param values 数据数组
* @return children
*/
Children in(boolean condition, String alias, KProperty<?> column, Object... values);
default Children notIn(KProperty<?> column, Collection<?> coll) {
return notIn(true, null, column, coll);
}
default Children notIn(String alias, KProperty<?> column, Collection<?> coll) {
return notIn(true, alias, column, coll);
}
default Children notIn(boolean condition, KProperty<?> column, Collection<?> coll) {
return notIn(condition, null, column, coll);
}
/**
* 字段 NOT IN (value.get(0), value.get(1), ...)
* <p>: notIn("id", Arrays.asList(1, 2, 3, 4, 5))</p>
*
* @param condition 执行条件
* @param column 字段
* @param coll 数据集合
* @return children
*/
Children notIn(boolean condition, String alias, KProperty<?> column, Collection<?> coll);
default Children notIn(KProperty<?> column, Object... value) {
return notIn(true, null, column, value);
}
default Children notIn(String alias, KProperty<?> column, Object... value) {
return notIn(true, alias, column, value);
}
default Children notIn(boolean condition, KProperty<?> column, Object... values) {
return notIn(condition, null, column, values);
}
/**
* 字段 NOT IN (v0, v1, ...)
* <p>: notIn("id", 1, 2, 3, 4, 5)</p>
*
* @param condition 执行条件
* @param column 字段
* @param values 数据数组
* @return children
*/
Children notIn(boolean condition, String alias, KProperty<?> column, Object... values);
default Children inSql(KProperty<?> column, String inValue) {
return inSql(true, null, column, inValue);
}
default Children inSql(String alias, KProperty<?> column, String inValue) {
return inSql(true, alias, column, inValue);
}
default Children inSql(boolean condition, KProperty<?> column, String inValue) {
return inSql(condition, null, column, inValue);
}
/**
* 字段 IN ( sql语句 )
* <p>!! sql 注入方式的 in 方法 !!</p>
* <p>例1: inSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例2: inSql("id", "select id from table where id &lt; 3")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句
* @return children
*/
Children inSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children notInSql(KProperty<?> column, String inValue) {
return notInSql(true, null, column, inValue);
}
default Children notInSql(String alias, KProperty<?> column, String inValue) {
return notInSql(true, alias, column, inValue);
}
default Children notInSql(boolean condition, KProperty<?> column, String inValue) {
return notInSql(condition, null, column, inValue);
}
/**
* 字段 NOT IN ( sql语句 )
* <p>!! sql 注入方式的 not in 方法 !!</p>
* <p>例1: notInSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例2: notInSql("id", "select id from table where id &lt; 3")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句 ---&gt; 1,2,3,4,5,6 或者 select id from table where id &lt; 3
* @return children
*/
Children notInSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children gtSql(KProperty<?> column, String inValue) {
return gtSql(true, null, column, inValue);
}
default Children gtSql(String alias, KProperty<?> column, String inValue) {
return gtSql(true, alias, column, inValue);
}
default Children gtSql(boolean condition, KProperty<?> column, String inValue) {
return gtSql(condition, null, column, inValue);
}
/**
* 字段 &gt; ( sql语句 )
* <p>例1: gtSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例1: gtSql("id", "select id from table where name = 'JunJun'")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句
* @return children
*/
Children gtSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children geSql(KProperty<?> column, String inValue) {
return geSql(true, null, column, inValue);
}
default Children geSql(String alias, KProperty<?> column, String inValue) {
return geSql(true, alias, column, inValue);
}
default Children geSql(boolean condition, KProperty<?> column, String inValue) {
return geSql(condition, null, column, inValue);
}
/**
* 字段 >= ( sql语句 )
* <p>例1: geSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例1: geSql("id", "select id from table where name = 'JunJun'")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句
* @return children
*/
Children geSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children ltSql(KProperty<?> column, String inValue) {
return ltSql(true, null, column, inValue);
}
default Children ltSql(String alias, KProperty<?> column, String inValue) {
return ltSql(true, alias, column, inValue);
}
default Children ltSql(boolean condition, KProperty<?> column, String inValue) {
return ltSql(condition, null, column, inValue);
}
/**
* 字段 &lt; ( sql语句 )
* <p>例1: ltSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例1: ltSql("id", "select id from table where name = 'JunJun'")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句
* @return children
*/
Children ltSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children leSql(KProperty<?> column, String inValue) {
return leSql(true, null, column, inValue);
}
default Children leSql(String alias, KProperty<?> column, String inValue) {
return leSql(true, alias, column, inValue);
}
default Children leSql(boolean condition, KProperty<?> column, String inValue) {
return leSql(condition, null, column, inValue);
}
/**
* 字段 <= ( sql语句 )
* <p>例1: leSql("id", "1, 2, 3, 4, 5, 6")</p>
* <p>例1: leSql("id", "select id from table where name = 'JunJun'")</p>
*
* @param condition 执行条件
* @param column 字段
* @param inValue sql语句
* @return children
*/
Children leSql(boolean condition, String alias, KProperty<?> column, String inValue);
default Children groupBy(List<KProperty<?>> column) {
return groupBy(true, null, column);
}
default Children groupBy(String alias, List<KProperty<?>> column) {
return groupBy(true, alias, column);
}
default Children groupBy(boolean condition, List<KProperty<?>> columns) {
return groupBy(condition, null, columns);
}
Children groupBy(boolean condition, String alias, List<KProperty<?>> columns);
default Children groupBy(KProperty<?>... columns) {
return groupBy(true, null, columns);
}
default Children groupBy(String alias, KProperty<?>... columns) {
return groupBy(true, alias, columns);
}
default Children groupBy(boolean condition, KProperty<?>... columns) {
return groupBy(condition, null, columns);
}
/**
* 分组GROUP BY 字段, ...
* <p>: groupBy("id", "name")</p>
*
* @param condition 执行条件
* @param columns 字段数组
* @return children
*/
Children groupBy(boolean condition, String alias, KProperty<?>... columns);
default Children orderByAsc(KProperty<?> column) {
return orderByAsc(true, (String) null, column);
}
default Children orderByAsc(String alias, KProperty<?> column) {
return orderByAsc(true, alias, column);
}
default Children orderByAsc(List<KProperty<?>> columns) {
return orderByAsc(true, null, columns);
}
default Children orderByAsc(String alias, List<KProperty<?>> columns) {
return orderByAsc(true, alias, columns);
}
default Children orderByAsc(boolean condition, List<KProperty<?>> columns) {
return orderByAsc(condition, null, columns);
}
Children orderByAsc(boolean condition, String alias, List<KProperty<?>> columns);
default Children orderByAsc(KProperty<?>... columns) {
return orderByAsc(true, null, columns);
}
default Children orderByAsc(String alias, KProperty<?>... columns) {
return orderByAsc(true, alias, columns);
}
/**
* 排序ORDER BY 字段, ... ASC
* <p>: orderByAsc("id", "name")</p>
*
* @param condition 执行条件
* @param columns 字段数组
* @return children
*/
default Children orderByAsc(boolean condition, KProperty<?>... columns) {
return orderBy(condition, true, null, columns);
}
default Children orderByAsc(boolean condition, String alias, KProperty<?>... columns) {
return orderBy(condition, true, alias, columns);
}
default Children orderByDesc(List<KProperty<?>> columns) {
return orderByDesc(true, null, columns);
}
default Children orderByDesc(String alias, List<KProperty<?>> columns) {
return orderByDesc(true, alias, columns);
}
default Children orderByDesc(boolean condition, List<KProperty<?>> columns) {
return orderByDesc(condition, null, columns);
}
Children orderByDesc(boolean condition, String alias, List<KProperty<?>> columns);
default Children orderByDesc(KProperty<?>... columns) {
return orderByDesc(true, null, columns);
}
default Children orderByDesc(String alias, KProperty<?>... columns) {
return orderByDesc(true, alias, columns);
}
/**
* 排序ORDER BY 字段, ... DESC
* <p>: orderByDesc("id", "name")</p>
*
* @param condition 执行条件
* @param columns 字段数组
* @return children
*/
default Children orderByDesc(boolean condition, KProperty<?>... columns) {
return orderBy(condition, false, null, columns);
}
default Children orderByDesc(boolean condition, String alias, KProperty<?>... columns) {
return orderBy(condition, false, alias, columns);
}
default Children orderBy(boolean condition, boolean isAsc, KProperty<?>... columns) {
return orderBy(condition, isAsc, null, columns);
}
/**
* 排序ORDER BY 字段, ...
* <p>: orderBy(true, "id", "name")</p>
*
* @param condition 执行条件
* @param isAsc 是否是 ASC 排序
* @param columns 字段数组
* @return children
*/
Children orderBy(boolean condition, boolean isAsc, String alias, KProperty<?>... columns);
default Children having(String sqlHaving, Object... params) {
return having(true, sqlHaving, params);
}
/**
* HAVING ( sql语句 )
* <p>例1: having("sum(age) &gt; 10")</p>
* <p>例2: having("sum(age) &gt; {0}", 10)</p>
*
* @param condition 执行条件
* @param sqlHaving sql 语句
* @param params 参数数组
* @return children
*/
Children having(boolean condition, String sqlHaving, Object... params);
default Children func(Consumer<Children> consumer) {
return func(true, consumer);
}
/**
* 消费函数
*
* @param consumer 消费函数
* @return children
* @since 3.3.1
*/
default Children func(boolean condition, Consumer<Children> consumer) {
return func(condition, consumer, null);
}
Children func(boolean condition, Consumer<Children> consumer, Consumer<Children> consumerElse);
}

View File

@ -1,250 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import kotlin.reflect.KProperty;
import java.io.Serializable;
/**
* 将原来的泛型R改成KProperty<?>, Object改为KProperty<?>
* 以及移除不会在ON语句中出现的条件 比如like相关 保留原来的like 只是不太可能会出现 on a.id like b.id 所以不会支持这种写法
* <p>
* {@link com.baomidou.mybatisplus.core.conditions.interfaces.Compare}
*
* @since 1.4.6
*/
@SuppressWarnings("unused")
public interface OnCompare<Children> extends Serializable {
default Children eq(KProperty<?> column, KProperty<?> val) {
return eq(true, null, column, null, val);
}
default Children eq(String alias, KProperty<?> column, KProperty<?> val) {
return eq(true, alias, column, null, val);
}
default Children eq(KProperty<?> column, String rightAlias, KProperty<?> val) {
return eq(true, null, column, rightAlias, val);
}
default Children eq(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return eq(true, alias, column, rightAlias, val);
}
default Children eq(boolean condition, KProperty<?> column, KProperty<?> val) {
return eq(condition, null, column, null, val);
}
default Children eq(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return eq(condition, alias, column, null, val);
}
default Children eq(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return eq(condition, null, column, rightAlias, val);
}
/**
* 等于 =
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children eq(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
default Children ne(KProperty<?> column, KProperty<?> val) {
return ne(true, null, column, null, val);
}
default Children ne(String alias, KProperty<?> column, KProperty<?> val) {
return ne(true, alias, column, null, val);
}
default Children ne(KProperty<?> column, String rightAlias, KProperty<?> val) {
return ne(true, null, column, rightAlias, val);
}
default Children ne(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return ne(true, alias, column, rightAlias, val);
}
default Children ne(boolean condition, KProperty<?> column, KProperty<?> val) {
return ne(condition, null, column, null, val);
}
default Children ne(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return ne(condition, alias, column, null, val);
}
default Children ne(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return ne(condition, null, column, rightAlias, val);
}
/**
* 不等于 &lt;&gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ne(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
default Children gt(KProperty<?> column, KProperty<?> val) {
return gt(true, null, column, null, val);
}
default Children gt(String alias, KProperty<?> column, KProperty<?> val) {
return gt(true, alias, column, null, val);
}
default Children gt(KProperty<?> column, String rightAlias, KProperty<?> val) {
return gt(true, null, column, rightAlias, val);
}
default Children gt(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return gt(true, alias, column, rightAlias, val);
}
default Children gt(boolean condition, KProperty<?> column, KProperty<?> val) {
return gt(condition, null, column, null, val);
}
default Children gt(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return gt(condition, alias, column, null, val);
}
default Children gt(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return gt(condition, null, column, rightAlias, val);
}
/**
* 大于 &gt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children gt(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
default Children ge(KProperty<?> column, KProperty<?> val) {
return ge(true, null, column, null, val);
}
default Children ge(String alias, KProperty<?> column, KProperty<?> val) {
return ge(true, alias, column, null, val);
}
default Children ge(KProperty<?> column, String rightAlias, KProperty<?> val) {
return ge(true, null, column, rightAlias, val);
}
default Children ge(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return ge(true, alias, column, rightAlias, val);
}
default Children ge(boolean condition, KProperty<?> column, KProperty<?> val) {
return ge(condition, null, column, null, val);
}
default Children ge(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return ge(condition, alias, column, null, val);
}
default Children ge(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return ge(condition, null, column, rightAlias, val);
}
/**
* 大于等于 &gt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children ge(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
default Children lt(KProperty<?> column, KProperty<?> val) {
return lt(true, null, column, null, val);
}
default Children lt(String alias, KProperty<?> column, KProperty<?> val) {
return lt(true, alias, column, null, val);
}
default Children lt(KProperty<?> column, String rightAlias, KProperty<?> val) {
return lt(true, null, column, rightAlias, val);
}
default Children lt(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return lt(true, alias, column, rightAlias, val);
}
default Children lt(boolean condition, KProperty<?> column, KProperty<?> val) {
return lt(condition, null, column, null, val);
}
default Children lt(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return lt(condition, alias, column, null, val);
}
default Children lt(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return lt(condition, null, column, rightAlias, val);
}
/**
* 小于 &lt;
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children lt(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
default Children le(KProperty<?> column, KProperty<?> val) {
return le(true, null, column, null, val);
}
default Children le(String alias, KProperty<?> column, KProperty<?> val) {
return le(true, alias, column, null, val);
}
default Children le(KProperty<?> column, String rightAlias, KProperty<?> val) {
return le(true, null, column, rightAlias, val);
}
default Children le(String alias, KProperty<?> column, String rightAlias, KProperty<?> val) {
return le(true, alias, column, rightAlias, val);
}
default Children le(boolean condition, KProperty<?> column, KProperty<?> val) {
return le(condition, null, column, null, val);
}
default Children le(boolean condition, String alias, KProperty<?> column, KProperty<?> val) {
return le(condition, alias, column, null, val);
}
default Children le(boolean condition, KProperty<?> column, String rightAlias, KProperty<?> val) {
return le(condition, null, column, rightAlias, val);
}
/**
* 小于等于 &lt;=
*
* @param condition 执行条件
* @param column 字段
* @param val
* @return children
*/
Children le(boolean condition, String alias, KProperty<?> column, String rightAlias, KProperty<?> val);
}

View File

@ -1,324 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.github.yulichang.extension.kt.segments.FuncArgs;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.enums.BaseFuncEnum;
import com.github.yulichang.wrapper.enums.DefaultFuncEnum;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.segments.*;
import kotlin.reflect.KProperty;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* 参考 {@link com.baomidou.mybatisplus.core.conditions.query.Query}
*
* @author yulichang
*/
@SuppressWarnings({"unused", "DuplicatedCode"})
public interface Query<Children> extends Serializable {
List<Select> getSelectColum();
Children getChildren();
Integer getIndex();
boolean isHasAlias();
String getAlias();
/**
* 过滤查询的字段信息(主键除外!)
* 推荐使用 selectFilter(Class, Predicate) 含主键
*
* @param predicate 过滤方式
* @return children
* @see Query#selectFilter(Class, Predicate)
*/
@Deprecated
default Children select(Class<?> entityClass, Predicate<TableFieldInfo> predicate) {
TableInfo info = TableHelper.getAssert(entityClass);
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(entityClass);
info.getFieldList().stream().filter(predicate).collect(Collectors.toList()).forEach(
i -> getSelectColum().add(new SelectNormal(cacheMap.get(i.getProperty()), getIndex(), isHasAlias(), getAlias())));
return getChildren();
}
/**
* 过滤查询的字段信息
* <p>例1: 只要 java 字段名以 "test" 开头的 -> select(i -> i.getProperty().startsWith("test"))</p>
* <p>例2: 只要 java 字段属性是 CharSequence 类型的 -> select(TableFieldInfo::isCharSequence)</p>
* <p>例3: 只要 java 字段没有填充策略的 -> select(i -> i.getFieldFill() == FieldFill.DEFAULT)</p>
* <p>例4: 要全部字段 -> select(i -> true)</p>
* <p>例5: 只要主键字段 -> select(i -> false)</p>
*
* @param predicate 过滤方式
* @return children
*/
default Children selectFilter(Class<?> entityClass, Predicate<SelectCache> predicate) {
TableInfo info = TableHelper.getAssert(entityClass);
List<SelectCache> cacheList = ColumnCache.getListField(entityClass);
cacheList.stream().filter(predicate).collect(Collectors.toList()).forEach(
i -> getSelectColum().add(new SelectNormal(i, getIndex(), isHasAlias(), getAlias())));
return getChildren();
}
Children select(KProperty<?>... columns);
/**
* String 查询
*
* @param columns
*/
default Children select(String... columns) {
getSelectColum().addAll(Arrays.stream(columns).map(i ->
new SelectString(i, null)).collect(Collectors.toList()));
return getChildren();
}
/**
* String 查询
*
* @param column
*/
default Children selectAs(String column, KProperty<?> alias) {
getSelectColum().add(new SelectString(column + Constant.AS + alias.getName(), alias.getName()));
return getChildren();
}
/**
* String 查询
*
* @param column
*/
default Children selectAs(String index, KProperty<?> column, KProperty<?> alias) {
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(KtUtils.ref(column));
SelectCache cache = cacheMap.get(column.getName());
getSelectColum().add(new SelectString(
index + Constants.DOT + cache.getColumn() + Constant.AS + alias.getName(), alias.getName()));
return getChildren();
}
/**
* 说明
* 比如我们需要查询用户表有10个字段然而我们只需要3个就够了用mybatis-plus提供的select<p />
* 需要一个属性一个属性填入很不优雅现在我们可以用selectAsClass(UserDO.class, UserVo.class)<p />
* 即可按所需的UserVo返回前提是UserVo.class中的属性必须是UserDO.class中存在的
*
* @param source 数据源实体类
* @param tag 目标类
* @return children
*/
default Children selectAsClass(Class<?> source, Class<?> tag) {
Map<String, SelectCache> normalMap = ColumnCache.getMapField(source);
List<FieldCache> fieldList = MPJReflectionKit.getFieldList(tag);
for (FieldCache cache : fieldList) {
if (normalMap.containsKey(cache.getField().getName())) {
SelectCache selectCache = normalMap.get(cache.getField().getName());
getSelectColum().add(new SelectNormal(selectCache, getIndex(), isHasAlias(), getAlias()));
}
}
return getChildren();
}
/**
* ignore
*/
default Children selectAs(KProperty<?> column, KProperty<?> alias) {
return selectAs(column, alias.getName());
}
/**
* 别名查询
*/
default Children selectAs(KProperty<?> column, String alias) {
Class<?> aClass = KtUtils.ref(column);
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(aClass);
getSelectColum().add(new SelectAlias(cacheMap.get(column.getName()), getIndex(), alias, isHasAlias(), getAlias()));
return getChildren();
}
/**
* 查询实体类全部字段
*/
default Children selectAll(Class<?> clazz) {
getSelectColum().addAll(ColumnCache.getListField(clazz).stream().map(i ->
new SelectNormal(i, getIndex(), isHasAlias(), getAlias())).collect(Collectors.toList()));
return getChildren();
}
/**
* 查询实体类全部字段
*/
default Children selectAll(Class<?> clazz, String prefix) {
getSelectColum().addAll(ColumnCache.getListField(clazz).stream().map(i ->
new SelectNormal(i, getIndex(), true, prefix)).collect(Collectors.toList()));
return getChildren();
}
/**
* select sql 片段
*/
String getSqlSelect();
/**
* 聚合函数查询
* <p>
* wrapper.selectFunc(() -> "COUNT(%s)", "t.id", "total");
* <p>
* lambda
* wrapper.selectFunc(() -> "COUNT(%s)", UserDO::getId, UserDTO::getTotal);
*
* @param funcEnum 函数枚举 {@link DefaultFuncEnum}
* @param column 函数作用的字段
* @param alias 别名
*/
default Children selectFunc(BaseFuncEnum funcEnum, Object column, String alias) {
getSelectColum().add(new SelectFunc(alias, getIndex(), funcEnum, column.toString(), isHasAlias(), getAlias()));
return getChildren();
}
default Children selectFunc(BaseFuncEnum funcEnum, KProperty<?> column, String alias) {
Class<?> aClass = KtUtils.ref(column);
Map<String, SelectCache> cacheMap = ColumnCache.getMapField(aClass);
getSelectColum().add(new SelectFunc(cacheMap.get(column.getName()), getIndex(), alias, funcEnum, isHasAlias(), getAlias()));
return getChildren();
}
default Children selectFunc(BaseFuncEnum funcEnum, KProperty<?> column, KProperty<?> alias) {
return selectFunc(funcEnum, column, alias.getName());
}
default Children selectFunc(BaseFuncEnum funcEnum, KProperty<?> column) {
return selectFunc(funcEnum, column, column);
}
default Children selectFunc(BaseFuncEnum funcEnum, Object column, KProperty<?> alias) {
return selectFunc(funcEnum, column, alias.getName());
}
Children selectFunc(String sql, MFunction<FuncArgs> column, String alias);
default Children selectFunc(String sql, MFunction<FuncArgs> column, KProperty<?> alias) {
return selectFunc(sql, column, alias.getName());
}
/* 默认聚合函数扩展 */
/**
* SUM()
*/
default Children selectSum(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.SUM, column);
}
default Children selectSum(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.SUM, column, alias);
}
default Children selectSum(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.SUM, column, alias);
}
/**
* COUNT()
*/
default Children selectCount(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.COUNT, column);
}
default Children selectCount(Object column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
default Children selectCount(Object column, String alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
default Children selectCount(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
default Children selectCount(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.COUNT, column, alias);
}
/**
* MAX()
*/
default Children selectMax(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.MAX, column);
}
default Children selectMax(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.MAX, column, alias);
}
default Children selectMax(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.MAX, column, alias);
}
/**
* MIN()
*/
default Children selectMin(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.MIN, column);
}
default Children selectMin(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.MIN, column, alias);
}
default Children selectMin(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.MIN, column, alias);
}
/**
* MIN()
*/
default Children selectAvg(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.AVG, column);
}
default Children selectAvg(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.AVG, column, alias);
}
default Children selectAvg(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.AVG, column, alias);
}
/**
* LEN()
*/
default Children selectLen(KProperty<?> column) {
return selectFunc(DefaultFuncEnum.LEN, column);
}
default Children selectLen(KProperty<?> column, KProperty<?> alias) {
return selectFunc(DefaultFuncEnum.LEN, column, alias);
}
default Children selectLen(KProperty<?> column, String alias) {
return selectFunc(DefaultFuncEnum.LEN, column, alias);
}
}

View File

@ -1,452 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.extension.kt.KtAbstractLambdaWrapper;
import com.github.yulichang.query.interfaces.StringJoin;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.wrapper.interfaces.MFunction;
import kotlin.reflect.KProperty;
import java.util.function.BiConsumer;
/**
* @author yulichang
*/
@SuppressWarnings("unused")
public interface QueryJoin<Children, Entity> extends MPJBaseJoin<Entity>, StringJoin<Children, Entity> {
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right) {
return join(Constant.LEFT_JOIN, clazz, left, right);
}
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.LEFT_JOIN, clazz, left, rightAlias, right);
}
/**
* left join 多条件
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param function 条件`
*/
default Children leftJoin(Class<?> clazz, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.LEFT_JOIN, clazz, function);
}
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.LEFT_JOIN, clazz, left, right, ext);
}
/**
* left join 多条件
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param consumer 条件
*/
default Children leftJoin(Class<?> clazz, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.LEFT_JOIN, clazz, consumer);
}
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right) {
return join(Constant.LEFT_JOIN, clazz, alias, left, right);
}
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, String alias, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.LEFT_JOIN, clazz, alias, left, rightAlias, right);
}
/**
* left join 多条件
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param function 条件
*/
default Children leftJoin(Class<?> clazz, String alias, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.LEFT_JOIN, clazz, alias, function);
}
/**
* left join
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children leftJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.LEFT_JOIN, clazz, alias, left, right, ext);
}
/**
* left join 多条件
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param consumer 条件
*/
default Children leftJoin(Class<?> clazz, String alias, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.LEFT_JOIN, clazz, alias, consumer);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right) {
return join(Constant.RIGHT_JOIN, clazz, left, right);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.RIGHT_JOIN, clazz, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.RIGHT_JOIN, clazz, function);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.RIGHT_JOIN, clazz, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.RIGHT_JOIN, clazz, consumer);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right) {
return join(Constant.RIGHT_JOIN, clazz, alias, left, right);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, String alias, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.RIGHT_JOIN, clazz, alias, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, String alias, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.RIGHT_JOIN, clazz, alias, function);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.RIGHT_JOIN, clazz, alias, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children rightJoin(Class<?> clazz, String alias, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.RIGHT_JOIN, clazz, alias, consumer);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right) {
return join(Constant.INNER_JOIN, clazz, on -> on.eq(left, right));
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.INNER_JOIN, clazz, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.INNER_JOIN, clazz, function);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.INNER_JOIN, clazz, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.INNER_JOIN, clazz, consumer);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right) {
return join(Constant.INNER_JOIN, clazz, alias, on -> on.eq(left, right));
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, String alias, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.INNER_JOIN, clazz, alias, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, String alias, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.INNER_JOIN, clazz, alias, function);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.INNER_JOIN, clazz, alias, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children innerJoin(Class<?> clazz, String alias, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.INNER_JOIN, clazz, alias, consumer);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right) {
return join(Constant.FULL_JOIN, clazz, left, right);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.FULL_JOIN, clazz, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.FULL_JOIN, clazz, function);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.FULL_JOIN, clazz, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.FULL_JOIN, clazz, consumer);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right) {
return join(Constant.FULL_JOIN, clazz, alias, left, right);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, String alias, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(Constant.FULL_JOIN, clazz, alias, left, rightAlias, right);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, String alias, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(Constant.FULL_JOIN, clazz, alias, function);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(Constant.FULL_JOIN, clazz, alias, left, right, ext);
}
/**
* ignore 参考 left join
*/
default Children fullJoin(Class<?> clazz, String alias, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(Constant.FULL_JOIN, clazz, alias, consumer);
}
/**
* 自定义连表关键词
* 调用此方法 keyword 前后需要带空格 比如 " LEFT JOIN " " RIGHT JOIN "
* <p>
* 查询基类 可以直接调用此方法实现以上所有功能
*
* @param keyWord 连表关键字
* @param clazz 连表实体类
* @param left 关联条件
* @param right 扩展 用于关联表的 select where
*/
default Children join(String keyWord, Class<?> clazz, KProperty<?> left, KProperty<?> right) {
return join(keyWord, clazz, on -> on.eq(left, right));
}
/**
* ignore
*/
default Children join(String keyWord, Class<?> clazz, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(keyWord, clazz, on -> on.eq(left, rightAlias, right));
}
/**
* 自定义连表关键词
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param function 条件
*/
default Children join(String keyWord, Class<?> clazz, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(keyWord, clazz, (on, e) -> function.apply(on));
}
/**
* 自定义连表关键词
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children join(String keyWord, Class<?> clazz, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(keyWord, clazz, (on, e) -> {
on.eq(left, right);
ext.apply(e);
});
}
/**
* 自定义连表关键词
* 调用此方法 keyword 前后需要带空格 比如 " LEFT JOIN " " RIGHT JOIN "
* <p>
* 查询基类 可以直接调用此方法实现以上所有功能
*
* @param keyWord 连表关键字
* @param clazz 连表实体类
* @param left 关联条件
* @param right 扩展 用于关联表的 select where
*/
default <T, X> Children join(String keyWord, Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right) {
return join(keyWord, clazz, alias, on -> on.eq(left, right));
}
/**
* ignore
*/
default <T, X> Children join(String keyWord, Class<?> clazz, String alias, KProperty<?> left, String rightAlias, KProperty<?> right) {
return join(keyWord, clazz, alias, on -> on.eq(left, rightAlias, right));
}
/**
* 自定义连表关键词
* <p>
* leftJoin(UserDO.class, on -> on.eq(UserDO::getId,UserAddressDO::getUserId).le().gt()...)
*
* @param clazz 关联实体类
* @param function 条件
*/
default Children join(String keyWord, Class<?> clazz, String alias, MFunction<KtAbstractLambdaWrapper<?, ?>> function) {
return join(keyWord, clazz, alias, (on, e) -> function.apply(on));
}
/**
* 自定义连表关键词
*
* @param clazz 关联的实体类
* @param left 条件
* @param right 条件
*/
default Children join(String keyWord, Class<?> clazz, String alias, KProperty<?> left, KProperty<?> right, MFunction<Children> ext) {
return join(keyWord, clazz, alias, (on, e) -> {
on.eq(left, right);
ext.apply(e);
});
}
/**
* 内部使用, 不建议直接调用
*/
default Children join(String keyWord, Class<?> clazz, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer) {
return join(keyWord, clazz, null, consumer);
}
/**
* 内部使用, 不建议直接调用
*/
Children join(String keyWord, Class<?> clazz, String alias, BiConsumer<KtAbstractLambdaWrapper<?, ?>, Children> consumer);
}

View File

@ -1,178 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.github.yulichang.extension.kt.resultmap.MybatisLabel;
import com.github.yulichang.extension.kt.resultmap.MybatisLabelFree;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.Label;
import kotlin.reflect.KProperty;
import java.util.Collection;
import java.util.Map;
/**
* 对一或对多查询
*
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings({"unused", "DuplicatedCode"})
public interface QueryLabel<Children> {
void addLabel(Label<?> label, boolean isCollection);
Children getChildren();
/**
* 一对多查询 调用此方法发必需要调用对应的 left join / right join ... 连表方法否则会报错
* <p>
* 举例 UserDO AddressDO 为一对多关系 UserDTO 为结果类
* <pre>
* MPJLambdaWrapper&lt;UserDO&gt; wrapper = new MPJLambdaWrapper&lt;UserDO&gt;();
* wrapper.selectAll(UserDO.class)
* .selectCollection(AddressDO.class, UserDTO::getAddressListDTO)
* .leftJoin(AddressDO.class, ...... )
* .eq(...)
* ...
* <pre/>
* 会自动将 AddressDO类中相同属性的字段 以mybatis<collection>的方式映射到UserDTO.addressListDTO属性中
*
* @since 1.3.0
*
* @param child 连表数据库实体类
* @param dtoField 包装类对应的属性
*/
default Children selectCollection(Class<?> child, KProperty<?> dtoField) {
return selectCollection(null, child, dtoField);
}
default Children selectCollection(String prefix, Class<?> child, KProperty<?> dtoField) {
String dtoFieldName = dtoField.getName();
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField));
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<?, ?> builder;
if (genericType == null || genericType.isAssignableFrom(child)) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, child, field.getType());
} else {
builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, child, field.getType(), genericType, true);
}
addLabel(builder.build(), true);
return getChildren();
}
/**
* 一对多查询 调用此方法发必需要调用对应的 left join / right join ... 连表方法否则会报错
* <p>
* 举例 UserDO AddressDO 为一对多关系 UserDTO 为结果类
* <pre>
* MPJLambdaWrapper&lt;UserDO&gt; wrapper = new MPJLambdaWrapper();
* wrapper.selectAll(UserDO.class)
* .selectCollection(AddressDO.class, UserDTO::getAddressListDTO, map -> map
* .id(AddressDO::getId, AddressDTO::getId) //如果属性名一致 可以传一个
* .result(AddressDO::getUserId) //如果属性名一致 可以传一个
* .result(AddressDO::getAddress, AddressDTO::getAddress))) //如果属性名一致 可以传一个
* .leftJoin(AddressDO.class, ...... )
* .eq(...)
* ...
* <pre/>
*
* 会自动将 AddressDO类中指定的字段 以mybatis<collection>的方式映射到UserDTO.addressListDTO属性中
*
* @since 1.3.0
*
* @param child 连表数据库实体类
* @param dtoField 包装类对应的属性
* @param collection collection标签内容
*/
default Children selectCollection(Class<?> child,
KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
return selectCollection(null, child, dtoField, collection);
}
default Children selectCollection(KProperty<?> dtoField, MFunction<MybatisLabelFree.Builder<?>> collection) {
//自由映射必须存在泛型Z
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabelFree.Builder<?> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), genericType);
MybatisLabelFree.Builder<?> czBuilder = collection.apply(builder);
addLabel(czBuilder.build(), true);
return getChildren();
}
default Children selectCollection(String prefix,
Class<?> child,
KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<?, ?> builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, child, field.getType(), genericType, false);
MybatisLabel.Builder<?, ?> czBuilder = collection.apply(builder);
addLabel(czBuilder.build(), true);
return getChildren();
}
/**
* 对一查询 用法参考 selectCollection
*
* @since 1.3.0
*/
default Children selectAssociation(Class<?> child, KProperty<?> dtoField) {
return selectAssociation(null, child, dtoField);
}
default Children selectAssociation(String prefix, Class<?> child, KProperty<?> dtoField) {
String dtoFieldName = dtoField.getName();
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField));
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<?, ?> builder;
builder = new MybatisLabel.Builder<>(StrUtils.isBlank(prefix) ? null : prefix,
dtoFieldName, child, field.getType(), (Class<?>) field.getType(), true);
addLabel(builder.build(), false);
return getChildren();
}
/**
* 对一查询 用法参考 selectCollection
*
* @since 1.3.0
*/
default Children selectAssociation(Class<?> child, KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
return selectAssociation(null, child, dtoField, collection);
}
default Children selectAssociation(KProperty<?> dtoField,
MFunction<MybatisLabelFree.Builder<?>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabelFree.Builder<?> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), (Class<?>) field.getType());
MybatisLabelFree.Builder<?> cfBuilder = collection.apply(builder);
addLabel(cfBuilder.build(), false);
return getChildren();
}
default Children selectAssociation(String prefix, Class<?> child, KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<?, ?> builder = new MybatisLabel.Builder<>(StrUtils.isBlank(prefix) ? null : prefix,
dtoFieldName, child, field.getType(), (Class<?>) field.getType(), false);
MybatisLabel.Builder<?, ?> cfBuilder = collection.apply(builder);
addLabel(cfBuilder.build(), false);
return getChildren();
}
}

View File

@ -1,84 +0,0 @@
package com.github.yulichang.extension.kt.interfaces;
import kotlin.reflect.KProperty;
import java.io.Serializable;
/**
* copy {@link com.baomidou.mybatisplus.core.conditions.update.Update}
*
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings("unused")
public interface Update<Children> extends Serializable {
/**
* ignore
*/
default Children set(KProperty<?> column, Object val) {
return set(true, column, val);
}
/**
* 设置 更新 SQL SET 片段
*
* @param condition 是否加入 set
* @param column 字段
* @param val
* @return children
*/
default Children set(boolean condition, KProperty<?> column, Object val) {
return set(condition, column, val, null);
}
/**
* ignore
*/
default Children set(KProperty<?> column, Object val, String mapping) {
return set(true, column, val, mapping);
}
/**
* 设置 更新 SQL SET 片段
*
* @param condition 是否加入 set
* @param column 字段
* @param val
* @param mapping : javaType=int,jdbcType=NUMERIC,typeHandler=xxx.xxx.MyTypeHandler
* @return children
*/
Children set(boolean condition, KProperty<?> column, Object val, String mapping);
default Children setIncrBy(KProperty<?> column, Number val) {
return setIncrBy(true, column, val);
}
Children setIncrBy(boolean condition, KProperty<?> column, Number val);
default Children setDecrBy(KProperty<?> column, Number val) {
return setDecrBy(true, column, val);
}
Children setDecrBy(boolean condition, KProperty<?> column, Number val);
/**
* ignore
*/
default Children setSql(String sql) {
return setSql(true, sql);
}
/**
* 设置 更新 SQL SET 片段
*
* @param sql set sql
* @return children
*/
Children setSql(boolean condition, String sql);
/**
* 获取 更新 SQL SET 片段
*/
String getSqlSet();
}

View File

@ -1,288 +0,0 @@
package com.github.yulichang.extension.kt.resultmap;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.segments.SelectCache;
import kotlin.reflect.KProperty;
import lombok.Getter;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* collection 标签 目前先支持这几个属性 后续在扩展
*
* @author yulichang
* @since 1.4.6
*/
@Getter
public class MybatisLabel<E, T> implements Label<T> {
private String index;
private String property;
private Class<E> entityClass;
private Class<?> javaType;
private Class<T> ofType;
private List<IResult> resultList;
/**
* wrapper里面的引用
*/
private List<Label<?>> mybatisLabels;
private MybatisLabel() {
}
@SuppressWarnings({"unused", "unchecked", "DuplicatedCode"})
public static class Builder<E, T> {
private final MybatisLabel<E, T> mybatisLabel;
/**
* 自动构建
*/
@SuppressWarnings("unchecked")
public Builder(String index, String property, Class<E> entityClass, Class<?> javaType) {
this.mybatisLabel = new MybatisLabel<>();
mybatisLabel.property = property;
mybatisLabel.index = index;
mybatisLabel.entityClass = entityClass;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = (Class<T>) entityClass;
mybatisLabel.resultList = new ArrayList<>();
mybatisLabel.mybatisLabels = new ArrayList<>();
autoBuild(true, entityClass, (Class<T>) entityClass);
}
/**
* 手动构建
*
* @param property property
* @param entityClass 数据库实体类
* @param javaType javaType
* @param ofType 映射类
* @param auto 自动映射数据库实体对应的字段
*/
public Builder(String index, String property, Class<E> entityClass, Class<?> javaType, Class<T> ofType, boolean auto) {
this.mybatisLabel = new MybatisLabel<>();
mybatisLabel.property = property;
mybatisLabel.index = index;
mybatisLabel.entityClass = entityClass;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = ofType;
mybatisLabel.resultList = new ArrayList<>();
mybatisLabel.mybatisLabels = new ArrayList<>();
autoBuild(auto, entityClass, ofType);
}
/**
* 映射实体全部字段
*/
public Builder<E, T> all() {
autoBuild(true, mybatisLabel.entityClass, mybatisLabel.ofType);
return this;
}
/**
* 映射实体字段过滤(含主键)
*/
public Builder<E, T> filter(Predicate<SelectCache> predicate) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(mybatisLabel.ofType);
ColumnCache.getListField(mybatisLabel.entityClass).stream().filter(predicate)
.filter(p -> fieldMap.containsKey(p.getColumProperty())).forEach(c ->
mybatisLabel.resultList.add(new Result.Builder<T>(c.isPk(), mybatisLabel.index, c).build()));
return this;
}
public Builder<E, T> id(KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(true, mybatisLabel.index);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> id(KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(true, mybatisLabel.index);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> result(KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(false, mybatisLabel.index);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<E, T> result(KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(false, mybatisLabel.index);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public <A, R, B extends Collection<R>> Builder<E, T> collection(Class<A> entityClass, KProperty<?> func) {
return collection(null, entityClass, func);
}
/**
* 嵌套
*/
public Builder<E, T> collection(String prefix, Class<?> entityClass, KProperty<?> func) {
String dtoFieldName = func.getName();
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(func));
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Builder<?, ?> builder;
if (genericType == null || genericType.isAssignableFrom(entityClass)) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new Builder<>(prefix, dtoFieldName, entityClass, field.getType());
} else {
builder = new Builder<>(prefix, dtoFieldName, entityClass, field.getType(), genericType, true);
}
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
public <A, R> Builder<E, T> collection(Class<A> entityClass, KProperty<?> func, MFunction<Builder<A, R>> mFunc) {
return collection(null, entityClass, func, mFunc);
}
/**
* 嵌套
*/
public <A, R> Builder<E, T> collection(KProperty<?> func,
MFunction<MybatisLabelFree.Builder<R>> mFunc) {
String dtoFieldName = func.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(func)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
MybatisLabelFree.Builder<R> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), ofType);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, R> Builder<E, T> collection(String prefix,
Class<A> entityClass,
KProperty<?> func,
MFunction<Builder<A, R>> mFunc) {
String dtoFieldName = func.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(func)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Class<R> ofType = (Class<R>) genericType;
Builder<A, R> builder = new Builder<>(prefix, dtoFieldName, entityClass, field.getType(), ofType, false);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
public <A> Builder<E, T> association(Class<A> child, KProperty<?> dtoField) {
return association(null, child, dtoField);
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(String index, Class<A> child, KProperty<?> dtoField) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField));
String dtoFieldName = dtoField.getName();
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
Builder<A, B> builder;
builder = new Builder<>(index, dtoFieldName, child, field.getType(), (Class<B>) field.getType(), true);
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
public <A, B> Builder<E, T> association(Class<A> child, KProperty<?> dtoField,
MFunction<Builder<A, B>> collection) {
return association(null, child, dtoField, collection);
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(KProperty<?> dtoField,
MFunction<MybatisLabelFree.Builder<B>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabelFree.Builder<B> builder = new MybatisLabelFree.Builder<>(dtoFieldName, field.getType(), (Class<B>) field.getType());
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public <A, B> Builder<E, T> association(String index, Class<A> child, KProperty<?> dtoField,
MFunction<Builder<A, B>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
Builder<A, B> builder = new Builder<>(index, dtoFieldName, child, field.getType(), (Class<B>) field.getType(), false);
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
public MybatisLabel<E, T> build() {
if (CollectionUtils.isEmpty(mybatisLabel.resultList)) {
autoBuild(true, mybatisLabel.entityClass, mybatisLabel.ofType);
}
return mybatisLabel;
}
private void autoBuild(boolean auto, Class<E> entityClass, Class<T> tagClass) {
TableInfo tableInfo = TableHelper.getAssert(entityClass);
Map<String, FieldCache> tagMap = MPJReflectionKit.getFieldMap(tagClass);
if (auto && !tagMap.isEmpty()) {
List<SelectCache> listField = ColumnCache.getListField(entityClass);
if (entityClass.isAssignableFrom(tagClass)) {
mybatisLabel.resultList.addAll(listField.stream().map(i -> {
Result result = new Result();
result.setId(i.isPk());
result.setIndex(mybatisLabel.index);
result.setProperty(i.getColumProperty());
result.setJavaType(i.getColumnType());
result.setJdbcType(i.getJdbcType());
result.setSelectNormal(i);
return result;
}).collect(Collectors.toList()));
} else {
for (SelectCache s : listField) {
FieldCache field = tagMap.get(s.getColumProperty());
if (Objects.nonNull(field)) {
Result result = new Result();
result.setId(s.isPk());
result.setIndex(mybatisLabel.index);
result.setProperty(s.getColumProperty());
result.setJavaType(field.getType());
result.setSelectNormal(s);
mybatisLabel.resultList.add(result);
}
}
}
}
}
}
}

View File

@ -1,273 +0,0 @@
package com.github.yulichang.extension.kt.resultmap;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.MFunction;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.resultmap.ResultList;
import com.github.yulichang.wrapper.segments.SelectCache;
import kotlin.reflect.KProperty;
import lombok.Getter;
import java.util.*;
import java.util.function.Predicate;
/**
* 无泛型约束 实现自由映射
*
* @author yulichang
* @since 1.4.6
*/
@Getter
public class MybatisLabelFree<T> implements Label<T> {
private String property;
private Class<?> javaType;
private Class<T> ofType;
private List<IResult> resultList;
/**
* wrapper里面的引用
*/
private List<Label<?>> mybatisLabels;
private MybatisLabelFree() {
}
@SuppressWarnings({"unused", "DuplicatedCode"})
public static class Builder<T> {
private final MybatisLabelFree<T> mybatisLabel;
/**
* 手动构建
*
* @param property property
* @param javaType javaType
* @param ofType 映射类
*/
public Builder(String property, Class<?> javaType, Class<T> ofType) {
this.mybatisLabel = new MybatisLabelFree<>();
mybatisLabel.property = property;
mybatisLabel.javaType = javaType;
mybatisLabel.ofType = ofType;
mybatisLabel.resultList = new ResultList();
mybatisLabel.mybatisLabels = new ArrayList<>();
}
public Builder<T> all(Class<?> entityClass) {
allBuild(null, entityClass);
return this;
}
public Builder<T> all(String prefix, Class<?> entityClass) {
allBuild(prefix, entityClass);
return this;
}
/**
* 映射实体字段过滤(含主键)
*/
public Builder<T> filter(Class<?> entityClass, Predicate<SelectCache> predicate) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(mybatisLabel.ofType);
ColumnCache.getListField(entityClass).stream().filter(predicate)
.filter(p -> fieldMap.containsKey(p.getColumProperty())).forEach(c ->
mybatisLabel.resultList.add(new Result.Builder<T>(false, null, c).build()));
return this;
}
/**
* 映射实体字段过滤(含主键)
*/
public Builder<T> filter(String prefix, Class<?> entityClass, Predicate<SelectCache> predicate) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(mybatisLabel.ofType);
ColumnCache.getListField(entityClass).stream().filter(predicate)
.filter(p -> fieldMap.containsKey(p.getColumProperty())).forEach(c ->
mybatisLabel.resultList.add(new Result.Builder<T>(false, prefix, c).build()));
return this;
}
public Builder<T> id(KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(true, null);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> id(KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(true, null);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> id(String index, KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(true, index);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> id(String index, KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(true, index);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(false, null);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(false, null);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(String index, KProperty<?> entity, KProperty<?> tag) {
Result.Builder<T> builder = new Result.Builder<>(false, index);
builder.column(entity).property(tag);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> result(String index, KProperty<?> entity) {
Result.Builder<T> builder = new Result.Builder<>(false, index);
builder.column(entity);
mybatisLabel.resultList.add(builder.build());
return this;
}
public Builder<T> collection(Class<?> entityClass, KProperty<?> func) {
return collection(null, entityClass, func);
}
/**
* 嵌套
*/
public Builder<T> collection(String prefix, Class<?> entityClass, KProperty<?> func) {
String dtoFieldName = func.getName();
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(func));
FieldCache field = fieldMap.get(dtoFieldName);
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<?, ?> builder;
if (genericType == null || genericType.isAssignableFrom(entityClass)) {
//找不到集合泛型 List List<?> List<Object> 直接查询数据库实体
builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, entityClass, field.getType());
} else {
builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, entityClass, field.getType(), genericType, true);
}
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
public Builder<T> collection(Class<?> entityClass, KProperty<?> func, MFunction<MybatisLabel.Builder<?, ?>> mFunc) {
return collection(null, entityClass, func, mFunc);
}
public Builder<T> collection(KProperty<?> func, MFunction<Builder<?>> mFunc) {
String dtoFieldName = func.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(func)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
Builder<?> builder = new Builder<>(dtoFieldName, field.getType(), genericType);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
/**
* 嵌套
*/
public Builder<T> collection(String prefix,
Class<?> entityClass,
KProperty<?> func,
MFunction<MybatisLabel.Builder<?, ?>> mFunc) {
String dtoFieldName = func.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(func)).get(dtoFieldName);
//获取集合泛型
Class<?> genericType = MPJReflectionKit.getGenericType(field.getField());
MybatisLabel.Builder<?, ?> builder = new MybatisLabel.Builder<>(prefix, dtoFieldName, entityClass, field.getType(), genericType, false);
mybatisLabel.mybatisLabels.add(mFunc.apply(builder).build());
return this;
}
public Builder<T> association(Class<?> child, KProperty<?> dtoField) {
return association(null, child, dtoField);
}
/**
* 嵌套
*/
public Builder<T> association(String index, Class<?> child, KProperty<?> dtoField) {
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField));
String dtoFieldName = dtoField.getName();
FieldCache field = fieldMap.get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<?, ?> builder;
builder = new MybatisLabel.Builder<>(index, dtoFieldName, child, field.getType(), (Class<?>) field.getType(), true);
mybatisLabel.mybatisLabels.add(builder.build());
return this;
}
public Builder<T> association(Class<?> child, KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
return association(null, child, dtoField, collection);
}
/**
* 嵌套
*/
public Builder<T> association(String index, Class<?> child, KProperty<?> dtoField,
MFunction<MybatisLabel.Builder<?, ?>> collection) {
String dtoFieldName = dtoField.getName();
FieldCache field = MPJReflectionKit.getFieldMap(KtUtils.ref(dtoField)).get(dtoFieldName);
Assert.isFalse(Collection.class.isAssignableFrom(field.getType()), "association 不支持集合类");
MybatisLabel.Builder<?, ?> builder = new MybatisLabel.Builder<>(index, dtoFieldName, child, field.getType(), (Class<?>) field.getType(), false);
mybatisLabel.mybatisLabels.add(collection.apply(builder).build());
return this;
}
public MybatisLabelFree<T> build() {
if (CollectionUtils.isEmpty(mybatisLabel.resultList)) {
TableInfo tableInfo = TableHelper.get(mybatisLabel.ofType);
Assert.notNull(tableInfo,
"无法自动映射, 找不到 <%s> 对应的表, 请使用 .all(xxx.class), id()或者result() 手动映射",
mybatisLabel.ofType.getSimpleName());
all(mybatisLabel.ofType);
}
return mybatisLabel;
}
private void allBuild(String prefix, Class<?> entityClass) {
Map<String, FieldCache> tagMap = MPJReflectionKit.getFieldMap(mybatisLabel.getOfType());
List<SelectCache> listField = ColumnCache.getListField(entityClass);
for (SelectCache s : listField) {
FieldCache field = tagMap.get(s.getColumProperty());
if (Objects.nonNull(field)) {
Result result = new Result();
result.setIndex(prefix);
result.setId(s.isPk());
result.setJavaType(field.getType());
result.setProperty(s.getColumProperty());
result.setSelectNormal(s);
mybatisLabel.resultList.add(result);
}
}
}
}
}

View File

@ -1,101 +0,0 @@
package com.github.yulichang.extension.kt.resultmap;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.segments.SelectCache;
import kotlin.reflect.KProperty;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.type.JdbcType;
import java.util.Map;
import java.util.Objects;
/**
* result 标签
*
* @author yulichang
* @since 1.4.6
*/
@Getter
@Setter(AccessLevel.PACKAGE)
public class Result implements IResult {
private boolean isId;
private String index;
private SelectCache selectNormal;
private String property;
private Class<?> javaType;
private JdbcType jdbcType;
public Result() {
}
@SuppressWarnings({"UnusedReturnValue", "unused"})
public static class Builder<T> {
private final Result result;
public Builder(boolean isId, String index) {
this.result = new Result();
result.isId = isId;
result.index = index;
}
public Builder(boolean isId, String index, SelectCache selectCache) {
this.result = new Result();
result.isId = isId;
result.index = index;
result.selectNormal = selectCache;
result.property = selectCache.getColumProperty();
result.javaType = selectCache.getColumnType();
result.jdbcType = selectCache.getJdbcType();
}
public Builder<T> property(KProperty<?> property) {
result.property = property.getName();
return this;
}
public <E> Builder<T> column(KProperty<?> column) {
Map<String, SelectCache> normalMap = ColumnCache.getMapField(KtUtils.ref(column));
String name = column.getName();
SelectCache normal = normalMap.get(name);
result.selectNormal = normal;
if (StrUtils.isBlank(result.property)) {
result.property = normal.getColumProperty();
}
if (Objects.isNull(result.javaType)) {
result.javaType = normal.getColumnType();
}
if (Objects.isNull(result.jdbcType)) {
result.jdbcType = normal.getJdbcType();
}
return this;
}
public Builder<T> javaType(Class<?> javaType) {
result.javaType = javaType;
return this;
}
public Builder<T> jdbcType(JdbcType jdbcType) {
result.jdbcType = jdbcType;
return this;
}
public Result build() {
return result;
}
}
}

View File

@ -1,40 +0,0 @@
package com.github.yulichang.extension.kt.segments;
import com.github.yulichang.toolkit.KtUtils;
import com.github.yulichang.wrapper.segments.SelectFunc;
import kotlin.reflect.KProperty;
import lombok.Data;
import java.util.Arrays;
/**
* 自定义函数列
*
* @author yulichang
* @since 1.4.6
*/
@Data
@SuppressWarnings("unused")
public class FuncArgs {
private KProperty<?>[] args;
private Object[] values;
public FuncArgs accept(KProperty<?>... kProperty) {
this.args = kProperty;
return this;
}
public FuncArgs values(Object... values) {
this.values = values;
return this;
}
public SelectFunc.Arg[] getFuncArg() {
return Arrays.stream(args).map(i ->
new SelectFunc.Arg(KtUtils.ref(i), i.getName(), false, null, i,false,null))
.toArray(SelectFunc.Arg[]::new);
}
}

View File

@ -1,150 +0,0 @@
package com.github.yulichang.extension.kt.toolkit;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.extension.kt.KtLambdaWrapper;
import com.github.yulichang.toolkit.LogicInfoUtils;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.sql.SqlScriptUtils;
import java.util.Objects;
import java.util.Optional;
/**
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings("DuplicatedCode")
public class KtWrapperUtils {
public static String buildSubSqlByWrapper(Class<?> clazz, KtLambdaWrapper<?> wrapper, String alias) {
TableInfo tableInfo = TableHelper.getAssert(clazz);
String first = Optional.ofNullable(wrapper.getSqlFirst()).orElse(StringPool.EMPTY);
boolean hasWhere = false;
String entityWhere = getEntitySql(tableInfo, wrapper);
if (StrUtils.isNotBlank(entityWhere)) {
hasWhere = true;
}
String mainLogic = mainLogic(hasWhere, clazz, wrapper);
if (StrUtils.isNotBlank(mainLogic)) {
hasWhere = true;
}
String subLogic = subLogic(hasWhere, wrapper);
if (StrUtils.isNotBlank(subLogic)) {
hasWhere = true;
}
String sqlSegment = (wrapper.getSqlSegment() != null && StrUtils.isNotBlank(wrapper.getSqlSegment())) ?
((wrapper.isEmptyOfNormal() ? StringPool.EMPTY : (hasWhere ? " AND " : " WHERE ")) + wrapper.getSqlSegment()) : StringPool.EMPTY;
String sqlComment = Optional.ofNullable(wrapper.getSqlComment()).orElse(StringPool.EMPTY);
return String.format(" (%s SELECT %s FROM %s %s %s %s %s %s %s) AS %s ",
first,
wrapper.getSqlSelect(),
wrapper.getTableName(tableInfo.getTableName()),
wrapper.getAlias(),
wrapper.getFrom(),
mainLogic,
subLogic,
sqlSegment,
sqlComment,
alias);
}
public static String buildUnionSqlByWrapper(Class<?> clazz, KtLambdaWrapper<?> wrapper) {
TableInfo tableInfo = TableHelper.getAssert(clazz);
String first = Optional.ofNullable(wrapper.getSqlFirst()).orElse(StringPool.EMPTY);
boolean hasWhere = false;
String entityWhere = getEntitySql(tableInfo, wrapper);
if (StrUtils.isNotBlank(entityWhere)) {
hasWhere = true;
}
String mainLogic = mainLogic(hasWhere, clazz, wrapper);
if (StrUtils.isNotBlank(mainLogic)) {
hasWhere = true;
}
String subLogic = subLogic(hasWhere, wrapper);
if (StrUtils.isNotBlank(subLogic)) {
hasWhere = true;
}
String sqlSegment = (wrapper.getSqlSegment() != null && StrUtils.isNotBlank(wrapper.getSqlSegment())) ?
((wrapper.isEmptyOfNormal() ? StringPool.EMPTY : (hasWhere ? " AND " : " WHERE ")) + wrapper.getSqlSegment()) : StringPool.EMPTY;
String sqlComment = Optional.ofNullable(wrapper.getSqlComment()).orElse(StringPool.EMPTY);
return String.format(" %s SELECT %s FROM %s %s %s %s %s %s %s ",
first,
wrapper.getSqlSelect(),
wrapper.getTableName(tableInfo.getTableName()),
wrapper.getAlias(),
wrapper.getFrom(),
mainLogic,
subLogic,
sqlSegment,
sqlComment);
}
private static <T> String formatParam(KtLambdaWrapper<T> wrapper, Object param) {
final String genParamName = Constants.WRAPPER_PARAM + wrapper.getParamNameSeq().incrementAndGet();
final String paramStr = wrapper.getParamAlias() + ".paramNameValuePairs." + genParamName;
wrapper.getParamNameValuePairs().put(genParamName, param);
return SqlScriptUtils.safeParam(paramStr, null);
}
private static String getEntitySql(TableInfo tableInfo, KtLambdaWrapper<?> wrapper) {
Object obj = wrapper.getEntity();
if (Objects.isNull(obj)) {
return StringPool.EMPTY;
}
StringBuilder sb = new StringBuilder(StringPool.EMPTY);
for (TableFieldInfo fieldInfo : tableInfo.getFieldList()) {
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo) && fieldInfo.isLogicDelete()) {
continue;
}
Object val;
try {
val = fieldInfo.getField().get(obj);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (Objects.isNull(val)) {
continue;
}
sb.append(" AND ").append(wrapper.getTableList().getPrefixByClass(obj.getClass())).append(Constants.DOT)
.append(fieldInfo.getColumn()).append(Constants.EQUALS).append(formatParam(wrapper, val));
}
//条件不为空 加上 where
if (sb.length() > 0) {
sb.delete(0, 4);
sb.insert(0, " WHERE ");
}
return sb.toString();
}
private static String mainLogic(boolean hasWhere, Class<?> clazz, KtLambdaWrapper<?> wrapper) {
if (!wrapper.getLogicSql()) {
return StringPool.EMPTY;
}
String info = LogicInfoUtils.getLogicInfo(null, clazz, true, wrapper.getAlias());
if (StrUtils.isNotBlank(info)) {
if (hasWhere) {
return " AND " + info;
}
return " WHERE " + info.substring(4);
}
return StringPool.EMPTY;
}
private static String subLogic(boolean hasWhere, KtLambdaWrapper<?> wrapper) {
String sql = wrapper.getSubLogicSql();
if (StrUtils.isNotBlank(sql)) {
if (hasWhere) {
return sql;
}
return " WHERE " + sql.substring(4);
}
return StringPool.EMPTY;
}
}

View File

@ -1,83 +0,0 @@
package com.github.yulichang.extension.kt.toolkit;
import com.github.yulichang.extension.kt.KtDeleteJoinWrapper;
import com.github.yulichang.extension.kt.KtLambdaWrapper;
import com.github.yulichang.extension.kt.KtUpdateJoinWrapper;
/**
* @author yulichang
* @since 1.4.6
*/
@SuppressWarnings("unused")
public final class KtWrappers {
/**
* KtWrappers.kt(User.class)
*/
public static <T> KtLambdaWrapper<T> query(Class<T> clazz) {
return new KtLambdaWrapper<>(clazz);
}
/**
* KtWrappers.kt("t", User.class)
*/
public static <T> KtLambdaWrapper<T> query(String alias, Class<T> clazz) {
return new KtLambdaWrapper<>(clazz, alias);
}
/**
* KtWrappers.kt(user)
*/
public static <T> KtLambdaWrapper<T> query(T entity) {
return new KtLambdaWrapper<>(entity);
}
/**
* KtWrappers.kt("t", user)
*/
public static <T> KtLambdaWrapper<T> query(String alias, T entity) {
return new KtLambdaWrapper<>(entity, alias);
}
/**
* KtWrappers.ktUpdate(User.class)
*/
public static <T> KtUpdateJoinWrapper<T> update(Class<T> clazz) {
return new KtUpdateJoinWrapper<>(clazz);
}
/**
* KtWrappers.ktUpdate("t", User.class)
*/
public static <T> KtUpdateJoinWrapper<T> update(String alias, Class<T> clazz) {
return new KtUpdateJoinWrapper<>(clazz, alias);
}
/**
* KtWrappers.ktUpdate(user)
*/
public static <T> KtUpdateJoinWrapper<T> update(T entity) {
return new KtUpdateJoinWrapper<>(entity);
}
/**
* KtWrappers.ktUpdate("t", user)
*/
public static <T> KtUpdateJoinWrapper<T> update(String alias, T entity) {
return new KtUpdateJoinWrapper<>(entity, alias);
}
/**
* KtWrappers.ktDelete(User.class)
*/
public static <T> KtDeleteJoinWrapper<T> delete(Class<T> clazz) {
return new KtDeleteJoinWrapper<>(clazz);
}
/**
* KtWrappers.ktUpdate("t", User.class)
*/
public static <T> KtDeleteJoinWrapper<T> delete(String alias, Class<T> clazz) {
return new KtDeleteJoinWrapper<>(clazz, alias);
}
}

View File

@ -1,5 +1,6 @@
package com.github.yulichang.injector;
import com.baomidou.mybatisplus.core.MybatisPlusVersion;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
@ -8,16 +9,16 @@ import com.baomidou.mybatisplus.core.injector.methods.*;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.github.yulichang.adapter.base.tookit.VersionUtils;
import com.github.yulichang.adapter.v3431.AbstractMethodV3431;
import com.github.yulichang.method.*;
import com.github.yulichang.toolkit.MPJTableMapperHelper;
import com.github.yulichang.toolkit.ReflectionKit;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.VersionUtils;
import com.github.yulichang.toolkit.reflect.GenericTypeUtils;
import lombok.Getter;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@ -27,7 +28,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
@ -38,9 +38,9 @@ import static java.util.stream.Collectors.toList;
* @author yulichang
* @see DefaultSqlInjector
*/
@Getter
public class MPJSqlInjector extends DefaultSqlInjector {
@Getter
private AbstractSqlInjector sqlInjector;
public MPJSqlInjector() {
@ -58,7 +58,7 @@ public class MPJSqlInjector extends DefaultSqlInjector {
@Deprecated
@SuppressWarnings({"unused", "DeprecatedIsStillUsed"})
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
if (VersionUtils.compare(VersionUtils.getVersion(), "3.4.3.2") >= 0) {
if (VersionUtils.compare(MybatisPlusVersion.getVersion(), "3.4.3.2") >= 0) {
throw ExceptionUtils.mpe("DefaultSqlInjector 的 getMethodList(Class<?> mapperClass) 方法已在 3.4.3.2+ 改为" +
"getMethodList(Class<?> mapperClass, TableInfo tableInfo)\n");
}
@ -84,13 +84,8 @@ public class MPJSqlInjector extends DefaultSqlInjector {
/**
* mybatis plus 3.4.3.2
* <p>
* Deprecated
* 3.5.6 getMethodList(Configuration, Class, TableInfo)
*/
@Override
@Deprecated
@SuppressWarnings({"deprecation", "DeprecatedIsStillUsed"})
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
if (Objects.nonNull(sqlInjector)) {
return methodFilter(sqlInjector.getMethodList(mapperClass, tableInfo));
@ -98,14 +93,6 @@ public class MPJSqlInjector extends DefaultSqlInjector {
return methodFilter(super.getMethodList(mapperClass, tableInfo));
}
@Override
public List<AbstractMethod> getMethodList(Configuration configuration, Class<?> mapperClass, TableInfo tableInfo) {
if (Objects.nonNull(sqlInjector)) {
return methodFilter(sqlInjector.getMethodList(configuration, mapperClass, tableInfo));
}
return methodFilter(super.getMethodList(configuration, mapperClass, tableInfo));
}
private List<AbstractMethod> methodFilter(List<AbstractMethod> list) {
String packageStr = SelectList.class.getPackage().getName();
List<String> methodList = Arrays.asList(
@ -127,7 +114,7 @@ public class MPJSqlInjector extends DefaultSqlInjector {
private List<AbstractMethod> getJoinMethod() {
List<AbstractMethod> list = new ArrayList<>();
if (VersionUtils.compare(VersionUtils.getVersion(), "3.5.0") >= 0) {
if (VersionUtils.compare(MybatisPlusVersion.getVersion(), "3.5.0") >= 0) {
list.add(new DeleteJoin(SqlMethod.DELETE_JOIN.getMethod()));
list.add(new UpdateJoin(SqlMethod.UPDATE_JOIN.getMethod()));
list.add(new UpdateJoinAndNull(SqlMethod.UPDATE_JOIN_AND_NULL.getMethod()));
@ -135,6 +122,9 @@ public class MPJSqlInjector extends DefaultSqlInjector {
list.add(new SelectJoinOne(SqlMethod.SELECT_JOIN_ONE.getMethod()));
list.add(new SelectJoinList(SqlMethod.SELECT_JOIN_LIST.getMethod()));
list.add(new SelectJoinPage(SqlMethod.SELECT_JOIN_PAGE.getMethod()));
list.add(new SelectJoinMap(SqlMethod.SELECT_JOIN_MAP.getMethod()));
list.add(new SelectJoinMaps(SqlMethod.SELECT_JOIN_MAPS.getMethod()));
list.add(new SelectJoinMapsPage(SqlMethod.SELECT_JOIN_MAPS_PAGE.getMethod()));
} else {
list.add(new DeleteJoin());
list.add(new UpdateJoin());
@ -143,6 +133,9 @@ public class MPJSqlInjector extends DefaultSqlInjector {
list.add(new SelectJoinOne());
list.add(new SelectJoinList());
list.add(new SelectJoinPage());
list.add(new SelectJoinMap());
list.add(new SelectJoinMaps());
list.add(new SelectJoinMapsPage());
}
return list;
}
@ -171,17 +164,15 @@ public class MPJSqlInjector extends DefaultSqlInjector {
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0);
Class<?> modelClass = getSuperClassGenericType(mapperClass, Mapper.class, 0);
super.inspectInject(builderAssistant, mapperClass);
MPJTableMapperHelper.init(modelClass, mapperClass);
Supplier<Class<?>> supplier = () -> {
try {
return extractModelClassOld(mapperClass);
} catch (Throwable throwable) {
return null;
}
};
TableHelper.init(modelClass, supplier.get());
TableHelper.init(modelClass, extractModelClassOld(mapperClass));
}
public static Class<?> getSuperClassGenericType(final Class<?> clazz, final Class<?> genericIfc, final int index) {
Class<?>[] typeArguments = GenericTypeUtils.resolveTypeArguments(ClassUtils.getUserClass(clazz), genericIfc);
return null == typeArguments ? null : typeArguments[index];
}
@SuppressWarnings("IfStatementWithIdenticalBranches")

View File

@ -1,31 +1,27 @@
package com.github.yulichang.interceptor;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.adapter.base.tookit.VersionUtils;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.toolkit.*;
import com.github.yulichang.method.MPJResultType;
import com.github.yulichang.query.MPJQueryWrapper;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.MPJReflectionKit;
import com.github.yulichang.toolkit.MPJTableMapperHelper;
import com.github.yulichang.toolkit.TableHelper;
import com.github.yulichang.toolkit.support.FieldCache;
import com.github.yulichang.wrapper.interfaces.SelectWrapper;
import com.github.yulichang.wrapper.resultmap.IResult;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.resultmap.Result;
import com.github.yulichang.wrapper.segments.Select;
import com.github.yulichang.wrapper.segments.SelectLabel;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultFlag;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
@ -35,8 +31,9 @@ import java.util.concurrent.ConcurrentHashMap;
/**
* 连表拦截器
* <p>
* 用于实现动态resultType
* 之前的实现方式是mybatis-plus的Interceptor,无法修改args,存在并发问题
* 所以将这个拦截器独立出来
*
* @author yulichang
*/
@ -44,76 +41,95 @@ import java.util.concurrent.ConcurrentHashMap;
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class MPJInterceptor implements Interceptor {
private static final boolean v = VersionUtils.compare(VersionUtils.getVersion(), "3.4.3.1") > 0;
private static final List<ResultMapping> EMPTY_RESULT_MAPPING = new ArrayList<>(0);
private static final Map<String, Val> MS_MAPPER_CACHE = new ConcurrentHashMap<>();
/**
* 缓存MappedStatement,不需要每次都去重新构建MappedStatement
*/
private static final Map<String, Map<Configuration, MappedStatement>> MS_CACHE = new ConcurrentHashMap<>();
private static final Map<String, Val> RES_MAPPER_CACHE = new ConcurrentHashMap<>();
private static final Log log = LogFactory.getLog(MPJInterceptor.class);
@Override
@SuppressWarnings("Java8MapApi")
public Object intercept(Invocation invocation) throws Throwable {
Object ew = null;
Object[] args = invocation.getArgs();
if (args[0] instanceof MappedStatement) {
MappedStatement ms = (MappedStatement) args[0];
if (args[1] instanceof Map) {
Map<String, Object> map = (Map<String, Object>) args[1];
ew = map.getOrDefault(Constants.WRAPPER, null);
if (Objects.nonNull(ew) && ew instanceof MPJBaseJoin) {
Class<?> rt = null;
if (map.containsKey(Constant.CLAZZ) && map.get(Constant.CLAZZ) != null) {
rt = (Class<?>) map.get(Constant.CLAZZ);
} else {
if (CollectionUtils.isNotEmpty(ms.getResultMaps())) {
Class<?> entity = MPJTableMapperHelper.getEntity(getMapper(ms.getId(), ms.getResource()));
Class<?> type = ms.getResultMaps().get(0).getType();
if (Objects.nonNull(entity) && Objects.nonNull(type)
&& !MPJReflectionKit.isPrimitiveOrWrapper(type) && (entity == type)) {
rt = type;
Object ew = map.containsKey(Constants.WRAPPER) ? map.get(Constants.WRAPPER) : null;
if (CollectionUtils.isNotEmpty(map) && map.containsKey(Constant.CLAZZ)) {
Class<?> clazz = (Class<?>) map.get(Constant.CLAZZ);
if (Objects.nonNull(clazz)) {
List<ResultMap> list = ms.getResultMaps();
if (CollectionUtils.isNotEmpty(list)) {
ResultMap resultMap = list.get(0);
if (resultMap.getType() == MPJResultType.class) {
args[0] = getMappedStatement(ms, clazz, ew);
}
}
}
if (Objects.nonNull(rt)) {
args[0] = getMappedStatement(ms, rt, ew, map);
}
}
}
}
return fill(ew, invocation.proceed());
return invocation.proceed();
}
/**
* 获取MappedStatement
*/
public <E> MappedStatement getMappedStatement(MappedStatement ms, Class<?> resultType, Object ew, Map<String, Object> map) {
if (ew instanceof SelectWrapper) {
SelectWrapper<E, ?> wrapper = (SelectWrapper<E, ?>) ew;
@SuppressWarnings("rawtypes")
public MappedStatement getMappedStatement(MappedStatement ms, Class<?> resultType, Object ew) {
String id = ms.getId() + StringPool.DASH + (resultType.getName().replaceAll("\\.", StringPool.DASH));
if (ew instanceof MPJLambdaWrapper) {
MPJLambdaWrapper wrapper = (MPJLambdaWrapper) ew;
if (wrapper.getEntityClass() == null) {
wrapper.setEntityClass((Class<E>) MPJTableMapperHelper.getEntity(getMapper(ms.getId(), ms.getResource())));
wrapper.setEntityClass(MPJTableMapperHelper.getEntity(getEntity(ms.getId())));
}
if (wrapper.getSelectColumns().isEmpty() && wrapper.getEntityClass() != null) {
wrapper.selectAll();
wrapper.selectAll(wrapper.getEntityClass());
}
if (wrapper.isResultMapCollection()) {
if (map.values().stream().anyMatch(a -> a instanceof IPage) && !wrapper.isPageByMain()) {
// 一对多分页问题警告
log.warn("select one to many and page query will result in errors in the total count statistics, please use xml.");
}
//TODO 重构缓存 -> 根据sql缓存
//不走缓存
}
if (ew instanceof MPJQueryWrapper) {
MPJQueryWrapper wrapper = (MPJQueryWrapper) ew;
if (ConfigProperties.msCache) {
return getCache(ms, id + StringPool.UNDERSCORE + removeDot(wrapper.getSqlSelect()), resultType, ew);
}
}
return buildMappedStatement(ms, resultType, ew);
return buildMappedStatement(ms, resultType, ew, id);
}
/**
* 走缓存
*/
private MappedStatement getCache(MappedStatement ms, String id, Class<?> resultType, Object ew) {
Map<Configuration, MappedStatement> statementMap = MS_CACHE.get(id);
if (CollectionUtils.isNotEmpty(statementMap)) {
MappedStatement statement = statementMap.get(ms.getConfiguration());
if (Objects.nonNull(statement)) {
return statement;
}
}
MappedStatement mappedStatement = buildMappedStatement(ms, resultType, ew, id);
if (statementMap == null) {
statementMap = new ConcurrentHashMap<>();
MS_CACHE.put(id, statementMap);
}
statementMap.put(ms.getConfiguration(), mappedStatement);
return mappedStatement;
}
/**
* 构建新的MappedStatement
*/
private MappedStatement buildMappedStatement(MappedStatement ms, Class<?> resultType, Object ew) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), ms.getSqlSource(), ms.getSqlCommandType())
private MappedStatement buildMappedStatement(MappedStatement ms, Class<?> resultType, Object ew, String id) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), id, ms.getSqlSource(), ms.getSqlCommandType())
.resource(ms.getResource())
.fetchSize(ms.getFetchSize())
.statementType(ms.getStatementType())
@ -135,6 +151,7 @@ public class MPJInterceptor implements Interceptor {
/**
* 构建resultMap TODO 可以用lambda简化代码
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private List<ResultMap> buildResultMap(MappedStatement ms, Class<?> resultType, Object obj) {
List<ResultMap> result = new ArrayList<>();
TableInfo tableInfo = TableHelper.get(resultType);
@ -143,12 +160,12 @@ public class MPJInterceptor implements Interceptor {
if (MPJReflectionKit.isPrimitiveOrWrapper(resultType)) {
return Collections.singletonList(new ResultMap.Builder(ms.getConfiguration(), id, resultType, EMPTY_RESULT_MAPPING).build());
}
if (!(obj instanceof SelectWrapper) || Map.class.isAssignableFrom(resultType) ||
if (!(obj instanceof MPJLambdaWrapper) || Map.class.isAssignableFrom(resultType) ||
Collection.class.isAssignableFrom(resultType)) {
result.add(getDefaultResultMap(tableInfo, ms, resultType, id));
return result;
}
SelectWrapper<?, ?> wrapper = (SelectWrapper<?, ?>) obj;
MPJLambdaWrapper wrapper = (MPJLambdaWrapper) obj;
Map<String, FieldCache> fieldMap = MPJReflectionKit.getFieldMap(resultType);
List<Select> columnList = wrapper.getSelectColumns();
//移除对多查询列为了可重复使用wrapper
@ -166,30 +183,18 @@ public class MPJInterceptor implements Interceptor {
}
} else {
FieldCache field = fieldMap.get(i.getColumProperty());
if (StrUtils.isNotBlank(i.getTagColumn())) {
columnSet.add(i.getTagColumn());
if (Objects.nonNull(field)) {
ResultMapping.Builder builder = new ResultMapping.Builder(ms.getConfiguration(), i.getColumProperty(),
i.getTagColumn(), field.getType());
resultMappings.add(selectToResult(wrapper.getEntityClass(), i, field.getType(), builder));
}
} else if (wrapper.isResultMap()) {
AdapterHelper.getAdapter().parserColum(wrapper.getAlias(), wrapper.getFrom(), i.getColumn(), col -> {
String tagCol = StrUtils.getTargetColumn(col);
FieldCache strField = fieldMap.get(tagCol);
columnSet.add(tagCol);
if (Objects.nonNull(strField)) {
ResultMapping.Builder builder = new ResultMapping.Builder(ms.getConfiguration(), tagCol,
tagCol, strField.getType());
resultMappings.add(selectToResult(wrapper.getEntityClass(), i, strField.getType(), builder));
}
});
columnSet.add(i.getTagColumn());
if (Objects.nonNull(field)) {
ResultMapping.Builder builder = new ResultMapping.Builder(ms.getConfiguration(), i.getColumProperty(),
i.getTagColumn(), field.getType());
resultMappings.add(selectToResult(wrapper.getEntityClass(), i, field.getType(), builder));
}
}
}
if (wrapper.isResultMap()) {
for (Label<?> o : wrapper.getResultMapMybatisLabel()) {
resultMappings.add(buildResult(ms, o, columnSet, columnList));
for (Object o : wrapper.getResultMapMybatisLabel()) {
Label<?> label = (Label<?>) o;
resultMappings.add(buildResult(ms, label, columnSet, columnList));
}
}
result.add(new ResultMap.Builder(ms.getConfiguration(), id, resultType, resultMappings).build());
@ -197,13 +202,8 @@ public class MPJInterceptor implements Interceptor {
}
private ResultMapping selectToResult(Class<?> entity, Select select, Class<?> type, ResultMapping.Builder builder) {
if (select.hasTypeHandle()) {
if (select.getPropertyType().isAssignableFrom(type)) {
builder.typeHandler(select.getTypeHandle());
} else {
throw new ClassCastException(String.format("%s not cast to %s [%s]",
select.getPropertyType().getSimpleName(), type.getSimpleName(), entity.getName() + "." + select.getColumProperty()));
}
if (select.hasTypeHandle() && select.getTableFieldInfo().getPropertyType().isAssignableFrom(type)) {
builder.typeHandler(select.getTypeHandle());
}
if (select.isPk() && entity == select.getClazz()) {
builder.flags(Collections.singletonList(ResultFlag.ID));
@ -219,7 +219,7 @@ public class MPJInterceptor implements Interceptor {
*/
private ResultMapping buildResult(MappedStatement ms, Label<?> mybatisLabel, Set<String> columnSet,
List<Select> columnList) {
List<IResult> resultList = mybatisLabel.getResultList();
List<Result> resultList = mybatisLabel.getResultList();
if (CollectionUtils.isEmpty(resultList)) {
return null;
}
@ -229,20 +229,20 @@ public class MPJInterceptor implements Interceptor {
.append(mybatisLabel.getProperty())
.append(StringPool.UNDERSCORE);
List<ResultMapping> childMapping = new ArrayList<>(resultList.size());
for (IResult r : resultList) {
for (Result r : resultList) {
childId.append("(");
Map<String, FieldCache> ofTypeField = MPJReflectionKit.getFieldMap(mybatisLabel.getOfType());
//列名去重
String columnName = r.getSelectNormal().getTagColumn();
String columnName = StringUtils.getTargetColumn(r.getSelectNormal().getColumn());
SelectLabel label;
FieldCache field = ofTypeField.get(r.getProperty());
String index = r.getIndex();
if (columnSet.contains(columnName)) {
columnName = getColumn(columnSet, columnName, 0);
label = new SelectLabel(r.getSelectNormal(), null, mybatisLabel.getOfType(), columnName, StrUtils.isNotBlank(index), index, r.getBaseColumn());
label = new SelectLabel(r.getSelectNormal(), null, mybatisLabel.getOfType(), columnName, StringUtils.isNotBlank(index), index);
} else {
columnSet.add(columnName);
label = new SelectLabel(r.getSelectNormal(), null, mybatisLabel.getOfType(), StrUtils.isNotBlank(index), index, r.getBaseColumn());
label = new SelectLabel(r.getSelectNormal(), null, mybatisLabel.getOfType(), StringUtils.isNotBlank(index), index);
}
columnList.add(label);
ResultMapping.Builder builder = new ResultMapping.Builder(ms.getConfiguration(), r.getProperty(), columnName, r.getJavaType());
@ -286,7 +286,7 @@ public class MPJInterceptor implements Interceptor {
childId.append("]");
}
//双检
String id = v ? childId.toString() : childId.toString().replaceAll("\\.", "~");
String id = childId.toString();
if (!ms.getConfiguration().hasResultMap(id)) {
ResultMap build = new ResultMap.Builder(ms.getConfiguration(), id, mybatisLabel.getOfType(), childMapping).build();
MPJInterceptor.addResultMap(ms, id, build);
@ -359,63 +359,27 @@ public class MPJInterceptor implements Interceptor {
}
}
private Object fill(Object ew, Object proceed) {
if (Objects.isNull(ew) || !(ew instanceof SelectWrapper<?, ?>) || MPJReflectionKit.isPrimitiveOrWrapper(proceed.getClass())) {
return proceed;
private Class<?> getEntity(String id) {
try {
return Class.forName(id.substring(0, id.lastIndexOf(StringPool.DOT)));
} catch (ClassNotFoundException e) {
return null;
}
if (proceed instanceof List) {
List<?> list = (List<?>) proceed;
if (!list.isEmpty()) {
Object o = list.stream().filter(Objects::nonNull).findFirst().orElse(null);
if (o == null || MPJReflectionKit.isPrimitiveOrWrapper(o.getClass())) {
return proceed;
}
}
}
SelectWrapper<?, ?> selectWrapper = (SelectWrapper<?, ?>) ew;
selectWrapper.doFill(proceed);
return proceed;
}
private Class<?> getMapper(String id, String resource) {
Class<?> clazz = MS_MAPPER_CACHE.computeIfAbsent(id, key -> {
try {
String className = key.substring(0, key.lastIndexOf(StringPool.DOT));
try {
return new Val(Class.forName(className));
} catch (ClassNotFoundException e) {
return new Val(MPJTableMapperHelper.getMapperForName(className));
}
} catch (Exception ignored) {
return new Val(null);
}
}).getVal();
if (Objects.nonNull(clazz)) {
return clazz;
private String removeDot(String str) {
if (StringUtils.isBlank(str)) {
return str;
} else {
return str.replaceAll("\\.", StringPool.DASH);
}
clazz = RES_MAPPER_CACHE.computeIfAbsent(resource, key -> {
try {
String className = key.substring(0, key.lastIndexOf(StringPool.DOT)).replaceAll("/", StringPool.DOT);
try {
return new Val(Class.forName(className));
} catch (ClassNotFoundException e) {
return new Val(MPJTableMapperHelper.getMapperForName(className));
}
} catch (Exception ignored) {
return new Val(null);
}
}).getVal();
return clazz;
}
@Override
public Object plugin(Object target) {
try {
return Interceptor.super.plugin(target);
} catch (Throwable e) {
} catch (Exception e) {
return Plugin.wrap(target, this);
}
}
@ -424,13 +388,7 @@ public class MPJInterceptor implements Interceptor {
public void setProperties(Properties properties) {
try {
Interceptor.super.setProperties(properties);
} catch (Throwable ignored) {
} catch (Exception ignored) {
}
}
@Data
@AllArgsConstructor
public static class Val {
private Class<?> val;
}
}

View File

@ -1,119 +0,0 @@
package com.github.yulichang.interceptor.pagination;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.extension.parser.JsqlParserGlobal;
import com.baomidou.mybatisplus.extension.plugins.pagination.DialectModel;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect;
import lombok.Getter;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.*;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.5.0
*/
public class DialectWrapper {
private final IDialect dialect;
@Getter
private final List<ParameterMapping> fullMappings = new ArrayList<>();
@Getter
private final List<ParameterMapping> pageMappings = new ArrayList<>();
@Getter
private String finallySql;
public DialectWrapper(IDialect dialect) {
this.dialect = dialect;
}
public void buildPaginationSql(String originalSql, List<ParameterMapping> mappings, long offset, long limit,
Consumer<DialectModel> consumers, MappedStatement ms, Object parameter) {
try {
// 解析sql
Select select = (Select) JsqlParserGlobal.parse(originalSql);
if (select instanceof SetOperationList) {
throw ExceptionUtils.mpe("不支持 union 对多分页");
}
//获取 ? 出现的次数
String sourceSql = select.toString();
int count = ParseHelper.countChar(sourceSql);
String formatSql;
if (count == mappings.size()) {
formatSql = ParseHelper.decode(sourceSql);
} else {
SqlSource sqlSource = ms.getSqlSource();
if (sqlSource instanceof DynamicSqlSource) {
formatSql = ParseHelper.getOriginalSql(parameter, (DynamicSqlSource) sqlSource);
} else {
throw ExceptionUtils.mpe("unknown type: " + sqlSource.getClass().getName());
}
}
//分页的sql
PlainSelect pageSql = (PlainSelect) JsqlParserGlobal.parse(formatSql);
List<Join> joins = pageSql.getJoins();
if (CollectionUtils.isNotEmpty(joins)) {
pageSql.setJoins(null);
}
pageSql.setSelectItems(Collections.singletonList(new SelectItem<>(new Column().withColumnName("*"))));
// 替换回 ? 同步mappings顺序
String repSql = pageSql.toString();
Map<Integer, ParameterMapping> sortMap = new HashMap<>();
repSql = ParseHelper.encode(mappings, count, repSql, sortMap);
this.pageMappings.addAll(sortMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).collect(Collectors.toList()));
DialectModel dialectModel = dialect.buildPaginationSql(repSql, offset, limit);
consumers.accept(dialectModel);
// 带分页方言的sql
String formatDialectSql = ParseHelper.decode(dialectModel.getDialectSql(), i -> "s" + i);
//完整的sql
PlainSelect fullSql = (PlainSelect) JsqlParserGlobal.parse(formatSql);
PlainSelect finalPlainSelect = new PlainSelect();
finalPlainSelect.setSelectItems(fullSql.getSelectItems());
finalPlainSelect.setDistinct(fullSql.getDistinct());
finalPlainSelect.setFromItem(
new Table()
.withName("(" + formatDialectSql + ")")
.withAlias(new Alias(fullSql.getFromItem().getAlias().getName(), false)));
finalPlainSelect.setJoins(fullSql.getJoins());
String finalSql = finalPlainSelect.toString();
Map<Integer, ParameterMapping> finalSortMap = new HashMap<>();
//page部分
for (int i = 0; i < count; i++) {
String repStr = ParseHelper.format.apply("s" + i);
int i1 = finalSql.indexOf(repStr);
if (i1 != -1) {
finalSql = finalSql.replace(repStr, "?");
finalSortMap.put(i1, this.pageMappings.get(i));
}
}
//其他部分
finalSql = ParseHelper.encode(mappings, count, finalSql, finalSortMap);
this.fullMappings.addAll(finalSortMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).collect(Collectors.toList()));
this.finallySql = finalSql;
} catch (Exception e) {
throw ExceptionUtils.mpe("not support this sql, please use xml. error sql: " + originalSql);
}
}
}

View File

@ -1,249 +0,0 @@
package com.github.yulichang.interceptor.pagination;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.parser.JsqlParserGlobal;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect;
import com.github.yulichang.wrapper.interfaces.SelectWrapper;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author yulichang
* @since 1.5.0
*/
public class PageInnerInterceptorWrapper extends PaginationInnerInterceptor {
private static final Log log = LogFactory.getLog(PageInnerInterceptorWrapper.class);
private final PaginationInnerInterceptor paginationInnerInterceptor;
public PageInnerInterceptorWrapper(PaginationInnerInterceptor pagination) {
this.paginationInnerInterceptor = pagination;
super.setOptimizeJoin(true);
super.setDbType(pagination.getDbType());
super.setDialect(pagination.getDialect());
super.setOverflow(pagination.isOverflow());
super.setMaxLimit(pagination.getMaxLimit());
}
/**
* 执行count
*/
@Override
public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (unusedPage(parameter)) {
return paginationInnerInterceptor.willDoQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
}
//没有wrapper 或者 不是对多查询 不做处理
SelectWrapper<?, ?> wrapper = findMPJWrapper(parameter).orElseThrow(RuntimeException::new);
// copy super
IPage<?> page = ParameterUtils.findPage(parameter).orElse(null);
if (page == null || page.getSize() < 0 || !page.searchCount() || resultHandler != Executor.NO_RESULT_HANDLER) {
return true;
}
BoundSql countSql;
MappedStatement countMs = buildCountMappedStatement(ms, page.countId());
if (countMs != null) {
countSql = countMs.getBoundSql(parameter);
} else {
countMs = buildAutoCountMappedStatement(ms);
ArrayList<ParameterMapping> mappingArrayList = new ArrayList<>(boundSql.getParameterMappings());
String countSqlStr = autoCountSql(boundSql.getSql(), mappingArrayList, ms, parameter, wrapper);
PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
countSql = new BoundSql(countMs.getConfiguration(), countSqlStr, mappingArrayList, parameter);
PluginUtils.setAdditionalParameter(countSql, mpBoundSql.additionalParameters());
}
CacheKey cacheKey = executor.createCacheKey(countMs, parameter, rowBounds, countSql);
List<Object> result = executor.query(countMs, parameter, rowBounds, resultHandler, cacheKey, countSql);
long total = 0;
if (CollectionUtils.isNotEmpty(result)) {
// 个别数据库 count 没数据不会返回 0
Object o = result.get(0);
if (o != null) {
total = Long.parseLong(o.toString());
}
}
page.setTotal(total);
return continuePage(page);
}
/**
* 添加分页方言
*/
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
if (unusedPage(parameter)) {
paginationInnerInterceptor.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
return;
}
// copy super
IPage<?> page = ParameterUtils.findPage(parameter).orElse(null);
if (null == page) {
return;
}
// 处理 orderBy 拼接
boolean addOrdered = false;
String buildSql = boundSql.getSql();
List<OrderItem> orders = page.orders();
if (CollectionUtils.isNotEmpty(orders)) {
addOrdered = true;
buildSql = this.concatOrderBy(buildSql, orders);
}
// size 小于 0 且不限制返回值则不构造分页sql
Long _limit = page.maxLimit() != null ? page.maxLimit() : maxLimit;
if (page.getSize() < 0 && null == _limit) {
if (addOrdered) {
PluginUtils.mpBoundSql(boundSql).sql(buildSql);
}
return;
}
handlerLimit(page, _limit);
DialectWrapper dialect = findMPJDialect(executor);
final Configuration configuration = ms.getConfiguration();
PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
Map<String, Object> additionalParameter = mpBoundSql.additionalParameters();
dialect.buildPaginationSql(buildSql, boundSql.getParameterMappings(), page.offset(), page.getSize(),
c -> c.consumers(dialect.getPageMappings(), configuration, additionalParameter),
ms, parameter);
mpBoundSql.sql(dialect.getFinallySql());
mpBoundSql.parameterMappings(dialect.getFullMappings());
}
private boolean unusedPage(Object parameter) {
return !findMPJWrapper(parameter).map(SelectWrapper::isPageByMain).orElse(false);
}
private String autoCountSql(String sql, List<ParameterMapping> mappings, MappedStatement ms, Object parameter, SelectWrapper<?, ?> wrapper) {
try {
Select select = (Select) JsqlParserGlobal.parse(sql);
if (select instanceof SetOperationList) {
throw ExceptionUtils.mpe("不支持 union 对多分页");
}
//获取 ? 出现的次数
String sourceSql = select.toString();
int count = ParseHelper.countChar(sourceSql);
String formatSql;
if (count == mappings.size()) {
formatSql = ParseHelper.decode(sourceSql);
} else {
SqlSource sqlSource = ms.getSqlSource();
if (sqlSource instanceof DynamicSqlSource) {
formatSql = ParseHelper.getOriginalSql(parameter, (DynamicSqlSource) sqlSource);
} else {
log.error("unknown type: " + sqlSource.getClass().getName());
throw ExceptionUtils.mpe("not support this sql, please use xml. error sql: " + sql);
}
}
PlainSelect ps = (PlainSelect) JsqlParserGlobal.parse(formatSql);
// 优化 order by 在非分组情况下
List<OrderByElement> orderBy = ps.getOrderByElements();
if (CollectionUtils.isNotEmpty(orderBy)) {
boolean canClean = true;
for (OrderByElement order : orderBy) {
// order by 里带参数,不去除order by
Expression expression = order.getExpression();
if (!(expression instanceof Column) && expression.toString().contains(StringPool.QUESTION_MARK)) {
canClean = false;
break;
}
}
if (canClean) {
ps.setOrderByElements(null);
}
}
List<Join> joins = ps.getJoins();
if (CollectionUtils.isNotEmpty(joins)) {
ps.setJoins(null);
}
String repSql;
Distinct distinct = ps.getDistinct();
GroupByElement groupBy = ps.getGroupBy();
String mainAlias = Optional.of(ps.getFromItem().getAlias().getName()).orElse("");
// 包含 distinctgroupBy 不优化
if (null != distinct || null != groupBy) {
if (wrapper.getPageInfo().getCountSelectSql() != null) {
ps.setSelectItems(Collections.singletonList(new SelectItem<>(new Column().withColumnName(wrapper.getPageInfo().getCountSelectSql()))));
} else {
ps.getSelectItems().removeIf(s -> {
if (s.getExpression() instanceof Column) {
Column column = (Column) s.getExpression();
return !mainAlias.equals(column.getTable().toString());
}
return false;
});
}
repSql = lowLevelCountSql(ps.toString());
} else {
// 优化 SQL
ps.setSelectItems(COUNT_SELECT_ITEM);
repSql = ps.toString();
}
// 替换回 ? 同步mappings顺序
Map<Integer, ParameterMapping> sortMap = new HashMap<>();
repSql = ParseHelper.encode(mappings, count, repSql, sortMap);
mappings.clear();
mappings.addAll(sortMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).collect(Collectors.toList()));
return repSql;
} catch (JSQLParserException e) {
logger.error("optimize this sql to a count sql has exception, sql:\"" + sql + "\", exception:\n" + e.getCause());
} catch (Exception e) {
logger.error("optimize this sql to a count sql has error, sql:\"" + sql + "\", exception:\n" + e);
}
throw ExceptionUtils.mpe("not support this sql, please use xml. error sql: " + sql);
}
private DialectWrapper findMPJDialect(Executor executor) {
IDialect dialect = super.findIDialect(executor);
return new DialectWrapper(dialect);
}
private static Optional<SelectWrapper<?, ?>> findMPJWrapper(Object parameterObject) {
if (parameterObject != null) {
if (parameterObject instanceof Map) {
Map<?, ?> parameterMap = (Map<?, ?>) parameterObject;
for (Map.Entry<?, ?> entry : parameterMap.entrySet()) {
if (entry.getValue() != null && entry.getValue() instanceof SelectWrapper) {
return Optional.of((SelectWrapper<?, ?>) entry.getValue());
}
}
} else if (parameterObject instanceof SelectWrapper) {
return Optional.of((SelectWrapper<?, ?>) parameterObject);
}
}
return Optional.empty();
}
}

View File

@ -1,111 +0,0 @@
package com.github.yulichang.interceptor.pagination;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.github.yulichang.toolkit.MPJReflectionKit;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.Configuration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* sql 分页解析工具类
*
* @author yulichang
* @since 1.5.0
*/
@SuppressWarnings("unused")
public final class ParseHelper {
private static final Map<SqlSource, SqlSourceWrapper> SQL_SOURCE_CACHE = new ConcurrentHashMap<>();
private static final String prefix = "MPJ_Param_i_";
private static final String suffix = "_MPJ_Param_i";
private static final char placeholder_char = '?';
private static final String placeholder_str = String.valueOf(placeholder_char);
public static final Function<Object, String> format = index -> prefix + index + suffix;
public static int countChar(String str) {
return countChar(str, placeholder_char);
}
public static int countChar(String str, String tag) {
return countChar(str, tag.charAt(0));
}
public static int countChar(String str, char tag) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == tag) {
count++;
}
}
return count;
}
public static String decode(String str) {
return decode(str, null);
}
public static String decode(String str, Function<Object, String> formatter) {
return decode(str, formatter, placeholder_char);
}
public static String decode(String str, Function<Object, String> formatter, char placeholder) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == placeholder) {
sb.append(format.apply(formatter == null ? count : formatter.apply(count)));
count++;
} else {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
public static String decode(String str, Function<Object, String> formatter, String placeholder) {
StringBuilder sb = new StringBuilder();
String[] split = str.split(placeholder);
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
if (i < split.length - 1) {
sb.append(format.apply(formatter == null ? i : formatter.apply(i)));
}
}
return sb.toString();
}
public static String encode(List<ParameterMapping> mappings, int count, String repSql, Map<Integer, ParameterMapping> sortMap) {
return encode(mappings, count, repSql, sortMap, placeholder_str);
}
public static String encode(List<ParameterMapping> mappings, int count, String repSql, Map<Integer, ParameterMapping> sortMap, String placeholder) {
for (int i = 0; i < count; i++) {
String repStr = ParseHelper.format.apply(i);
int i1 = repSql.indexOf(repStr);
if (i1 != -1) {
repSql = repSql.replace(repStr, placeholder);
sortMap.put(i1, mappings.get(i));
}
}
return repSql;
}
public static String getOriginalSql(Object parameter, DynamicSqlSource sqlSource) {
Assert.notNull(sqlSource, "sqlSource must not be null");
SqlSourceWrapper sqlSourceWrapper = SQL_SOURCE_CACHE.computeIfAbsent(sqlSource, key -> {
Configuration configuration = MPJReflectionKit.getFieldValue(sqlSource, "configuration");
SqlNode sqlNode = MPJReflectionKit.getFieldValue(sqlSource, "rootSqlNode");
return new SqlSourceWrapper(configuration, sqlNode);
});
return ParseHelper.decode(sqlSourceWrapper.getSql(parameter), null, ParseHelper.format.apply(""));
}
}

View File

@ -1,159 +0,0 @@
package com.github.yulichang.interceptor.pagination;
import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.builder.ParameterExpression;
import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author yulichang
* @since 1.5.0
*/
public class SqlSourceWrapper {
private static final String PARAMETER_PROPERTIES = "javaType,jdbcType,mode,numericScale,resultMap,typeHandler,jdbcTypeName";
private final Configuration configuration;
private final SqlNode rootSqlNode;
public SqlSourceWrapper(Configuration configuration, SqlNode rootSqlNode) {
this.configuration = configuration;
this.rootSqlNode = rootSqlNode;
}
public String getSql(Object parameterObject) {
DynamicContext context = new DynamicContext(configuration, parameterObject);
rootSqlNode.apply(context);
Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
return parse(context.getSql(), parameterType, context.getBindings());
}
public String parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType,
additionalParameters) {
@Override
public String handleToken(String content) {
super.handleToken(content);
return ParseHelper.format.apply("");
}
};
GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
String sql;
if (configuration.isShrinkWhitespacesInSql()) {
sql = parser.parse(SqlSourceBuilder.removeExtraWhitespaces(originalSql));
} else {
sql = parser.parse(originalSql);
}
return sql;
}
/**
* copy {@link org.apache.ibatis.builder.SqlSourceBuilder.ParameterMappingTokenHandler}
*/
@SuppressWarnings("all")
private static class ParameterMappingTokenHandler extends BaseBuilder implements TokenHandler {
private final List<ParameterMapping> parameterMappings = new ArrayList<>();
private final Class<?> parameterType;
private final MetaObject metaParameters;
public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType,
Map<String, Object> additionalParameters) {
super(configuration);
this.parameterType = parameterType;
this.metaParameters = configuration.newMetaObject(additionalParameters);
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
@Override
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
private ParameterMapping buildParameterMapping(String content) {
Map<String, String> propertiesMap = parseParameterMapping(content);
String property = propertiesMap.get("property");
Class<?> propertyType;
if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
propertyType = metaParameters.getGetterType(property);
} else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
propertyType = parameterType;
} else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
propertyType = java.sql.ResultSet.class;
} else if (property == null || Map.class.isAssignableFrom(parameterType)) {
propertyType = Object.class;
} else {
MetaClass metaClass = MetaClass.forClass(parameterType, configuration.getReflectorFactory());
if (metaClass.hasGetter(property)) {
propertyType = metaClass.getGetterType(property);
} else {
propertyType = Object.class;
}
}
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
Class<?> javaType = propertyType;
String typeHandlerAlias = null;
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if ("javaType".equals(name)) {
javaType = resolveClass(value);
builder.javaType(javaType);
} else if ("jdbcType".equals(name)) {
builder.jdbcType(resolveJdbcType(value));
} else if ("mode".equals(name)) {
builder.mode(resolveParameterMode(value));
} else if ("numericScale".equals(name)) {
builder.numericScale(Integer.valueOf(value));
} else if ("resultMap".equals(name)) {
builder.resultMapId(value);
} else if ("typeHandler".equals(name)) {
typeHandlerAlias = value;
} else if ("jdbcTypeName".equals(name)) {
builder.jdbcTypeName(value);
} else if ("property".equals(name)) {
// Do Nothing
} else if ("expression".equals(name)) {
throw new BuilderException("Expression based parameters are not supported yet");
} else {
throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content
+ "}. Valid properties are " + PARAMETER_PROPERTIES);
}
}
if (typeHandlerAlias != null) {
builder.typeHandler(resolveTypeHandler(javaType, typeHandlerAlias));
}
return builder.build();
}
private Map<String, String> parseParameterMapping(String content) {
try {
return new ParameterExpression(content);
} catch (BuilderException ex) {
throw ex;
} catch (Exception ex) {
throw new BuilderException("Parsing error was found in mapping #{" + content
+ "}. Check syntax #{property|(expression), var1=value1, var2=value2, ...} ", ex);
}
}
}
}

View File

@ -28,16 +28,16 @@ public class DeleteJoin extends MPJAbstractMethod {
@SuppressWarnings("DuplicatedCode")
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_JOIN;
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo)) {
if (AdapterHelper.getTableInfoAdapter().mpjHasLogic(tableInfo)) {
String sql = String.format(sqlMethod.getSql(), sqlFirst(), mpjTableName(tableInfo), sqlAlias(), sqlFrom(),
mpjDeleteLogic(tableInfo), sqlWhereEntityWrapper(true, tableInfo), sqlComment());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, removeExtraWhitespaces(sql), modelClass);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
} else {
sqlMethod = SqlMethod.DELETE_JOIN;
String sql = String.format(sqlMethod.getSql(), sqlFirst(), mpjDelete(), mpjTableName(tableInfo),
sqlAlias(), sqlFrom(), sqlWhereEntityWrapper(true, tableInfo), sqlComment());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, removeExtraWhitespaces(sql), modelClass);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addDeleteMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource);
}
}

View File

@ -6,11 +6,9 @@ import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.github.yulichang.adapter.v352.AbstractMethod352;
import com.github.yulichang.config.ConfigProperties;
import org.apache.ibatis.builder.SqlSourceBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author yulichang
@ -84,22 +82,4 @@ public abstract class MPJAbstractMethod extends AbstractMethod352 implements MPJ
return "";
}
}
public String removeExtraWhitespaces(String sql) {
try {
return SqlSourceBuilder.removeExtraWhitespaces(sql);
} catch (Throwable t) {
StringTokenizer tokenizer = new StringTokenizer(sql);
StringBuilder builder = new StringBuilder();
boolean hasMoreTokens = tokenizer.hasMoreTokens();
while (hasMoreTokens) {
builder.append(tokenizer.nextToken());
hasMoreTokens = tokenizer.hasMoreTokens();
if (hasMoreTokens) {
builder.append(' ');
}
}
return builder.toString();
}
}
}

View File

@ -1,23 +1,24 @@
package com.github.yulichang.method;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.core.MybatisPlusVersion;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.github.yulichang.adapter.AdapterHelper;
import com.github.yulichang.adapter.base.metadata.OrderFieldInfo;
import com.github.yulichang.annotation.DynamicTableName;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.toolkit.StrUtils;
import com.github.yulichang.toolkit.VersionUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static java.util.stream.Collectors.joining;
@ -30,7 +31,7 @@ import static java.util.stream.Collectors.joining;
public interface MPJBaseMethod extends Constants {
default String mpjSqlWhereEntityWrapper(boolean newLine, TableInfo table) {
if (AdapterHelper.getAdapter().mpjHasLogic(table)) {
if (ConfigProperties.tableInfoAdapter.mpjHasLogic(table)) {
String sqlScript = getAllSqlWhere(table, true, true, WRAPPER_ENTITY_DOT);
sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", WRAPPER_ENTITY), true);
sqlScript += NEWLINE;
@ -71,19 +72,23 @@ public interface MPJBaseMethod extends Constants {
*/
default String mpjSqlOrderBy(TableInfo tableInfo) {
/* 不存在排序字段,直接返回空 */
List<OrderFieldInfo> orderByFields;
List<TableFieldInfo> orderByFields;
try {
orderByFields = AdapterHelper.getAdapter().mpjGetOrderField(tableInfo);
if (VersionUtils.compare(MybatisPlusVersion.getVersion(), "3.4.3") >= 0) {
orderByFields = tableInfo.getOrderByFields();
} else {
return StringPool.EMPTY;
}
} catch (Exception e) {
return StringPool.EMPTY;
}
if (CollectionUtils.isEmpty(orderByFields)) {
return StringPool.EMPTY;
}
orderByFields.sort(Comparator.comparingInt(OrderFieldInfo::getSort));
orderByFields.sort(Comparator.comparingInt(TableFieldInfo::getOrderBySort));
String sql = NEWLINE + " ORDER BY " +
orderByFields.stream().map(tfi -> String.format("${ew.alias}.%s %s", tfi.getColumn(),
tfi.getType())).collect(joining(","));
tfi.getOrderByType())).collect(joining(","));
/* 当wrapper中传递了orderBy属性@orderBy注解失效 */
return SqlScriptUtils.convertIf(sql, String.format("%s == null or %s", WRAPPER,
WRAPPER_EXPRESSION_ORDER), true);
@ -98,16 +103,16 @@ public interface MPJBaseMethod extends Constants {
String filedSqlScript = tableInfo.getFieldList().stream()
.filter(i -> {
if (ignoreLogicDelFiled) {
return !(AdapterHelper.getAdapter().mpjHasLogic(tableInfo) && i.isLogicDelete());
return !(ConfigProperties.tableInfoAdapter.mpjHasLogic(tableInfo) && i.isLogicDelete());
}
return true;
})
.map(i -> getSqlWhere(i, newPrefix)).filter(Objects::nonNull).collect(joining(NEWLINE));
if (!withId || StrUtils.isBlank(tableInfo.getKeyProperty())) {
if (!withId || StringUtils.isBlank(tableInfo.getKeyProperty())) {
return filedSqlScript;
}
String newKeyProperty = newPrefix + tableInfo.getKeyProperty();
String keySqlScript = "${ew.alias}" + DOT + tableInfo.getKeyColumn() + EQUALS +
String keySqlScript = ConfigProperties.tableAlias + DOT + tableInfo.getKeyColumn() + EQUALS +
SqlScriptUtils.safeParam(newKeyProperty);
return SqlScriptUtils.convertIf(keySqlScript, String.format("%s != null", newKeyProperty), false)
+ NEWLINE + filedSqlScript;
@ -116,22 +121,18 @@ public interface MPJBaseMethod extends Constants {
default String getSqlWhere(TableFieldInfo tableFieldInfo, final String prefix) {
final String newPrefix = prefix == null ? EMPTY : prefix;
// 默认: AND column=#{prefix + el}
String sqlScript = " AND " + String.format(tableFieldInfo.getCondition(), "${ew.alias}" + DOT +
String sqlScript = " AND " + String.format(tableFieldInfo.getCondition(), ConfigProperties.tableAlias + DOT +
tableFieldInfo.getColumn(), newPrefix + tableFieldInfo.getEl());
// 查询的时候只判非空
return convertIf(tableFieldInfo, sqlScript, convertIfProperty(newPrefix, tableFieldInfo.getProperty()),
tableFieldInfo.getWhereStrategy());
}
@SuppressWarnings("DuplicatedCode")
default String convertIf(TableFieldInfo tableFieldInfo, final String sqlScript, final String property, final FieldStrategy fieldStrategy) {
if (fieldStrategy == FieldStrategy.NEVER) {
return null;
}
FieldStrategy strategy = Optional.ofNullable(fieldStrategy).orElse(FieldStrategy.DEFAULT);
if (AdapterHelper.getAdapter().mpjIsPrimitive(tableFieldInfo)
|| strategy.name().equalsIgnoreCase("ALWAYS")
|| strategy.name().equalsIgnoreCase("IGNORED")) {
if (ConfigProperties.tableInfoAdapter.mpjIsPrimitive(tableFieldInfo) || fieldStrategy == FieldStrategy.IGNORED) {
return sqlScript;
}
if (fieldStrategy == FieldStrategy.NOT_EMPTY && tableFieldInfo.isCharSequence()) {
@ -142,12 +143,12 @@ public interface MPJBaseMethod extends Constants {
}
default String convertIfProperty(String prefix, String property) {
return StrUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) + "['" + property + "']" : property;
return StringUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) + "['" + property + "']" : property;
}
default String getLogicDeleteSql(TableInfo tableInfo, boolean startWithAnd, boolean isWhere) {
if (AdapterHelper.getAdapter().mpjHasLogic(tableInfo)) {
if (ConfigProperties.tableInfoAdapter.mpjHasLogic(tableInfo)) {
String logicDeleteSql = formatLogicDeleteSql(tableInfo, isWhere);
if (startWithAnd) {
logicDeleteSql = " AND " + logicDeleteSql;
@ -159,15 +160,15 @@ public interface MPJBaseMethod extends Constants {
default String formatLogicDeleteSql(TableInfo tableInfo, boolean isWhere) {
final String value = isWhere ? AdapterHelper.getAdapter().mpjGetLogicField(tableInfo).getLogicNotDeleteValue() :
AdapterHelper.getAdapter().mpjGetLogicField(tableInfo).getLogicDeleteValue();
final String value = isWhere ? ConfigProperties.tableInfoAdapter.mpjGetLogicField(tableInfo).getLogicNotDeleteValue() :
ConfigProperties.tableInfoAdapter.mpjGetLogicField(tableInfo).getLogicDeleteValue();
if (isWhere) {
if (NULL.equalsIgnoreCase(value)) {
return "${ew.alias}." + AdapterHelper.getAdapter().mpjGetLogicField(tableInfo).getColumn() +
return "${ew.alias}." + ConfigProperties.tableInfoAdapter.mpjGetLogicField(tableInfo).getColumn() +
" IS NULL";
} else {
return "${ew.alias}." + AdapterHelper.getAdapter().mpjGetLogicField(tableInfo).getColumn() +
EQUALS + String.format(AdapterHelper.getAdapter().mpjGetLogicField(tableInfo).isCharSequence() ?
return "${ew.alias}." + ConfigProperties.tableInfoAdapter.mpjGetLogicField(tableInfo).getColumn() +
EQUALS + String.format(ConfigProperties.tableInfoAdapter.mpjGetLogicField(tableInfo).isCharSequence() ?
"'%s'" : "%s", value);
}
}
@ -187,6 +188,10 @@ public interface MPJBaseMethod extends Constants {
* 获取表名
*/
default String mpjTableName(TableInfo tableInfo) {
DynamicTableName dynamicTableName = tableInfo.getEntityType().getAnnotation(DynamicTableName.class);
if (Objects.isNull(dynamicTableName)) {
return tableInfo.getTableName();
}
String tableName = tableInfo.getTableName(), encode;
try {
encode = URLEncoder.encode(tableName, "UTF-8");
@ -226,7 +231,7 @@ public interface MPJBaseMethod extends Constants {
return tableInfo.getFieldList().stream()
.filter(i -> {
if (ignoreLogicDelFiled) {
return !(AdapterHelper.getAdapter().mpjHasLogic(tableInfo) && i.isLogicDelete());
return !(AdapterHelper.getTableInfoAdapter().mpjHasLogic(tableInfo) && i.isLogicDelete());
}
return true;
}).map(i -> mpjGetSqlSet(i, newPrefix)).filter(Objects::nonNull).collect(joining(NEWLINE));
@ -253,7 +258,7 @@ public interface MPJBaseMethod extends Constants {
final String newPrefix = prefix == null ? EMPTY : prefix;
// 默认: column=
String sqlSet = "${ew.alias}." + tableFieldInfo.getColumn() + EQUALS;
if (StrUtils.isNotBlank(tableFieldInfo.getUpdate())) {
if (StringUtils.isNotBlank(tableFieldInfo.getUpdate())) {
sqlSet += String.format(tableFieldInfo.getUpdate(), tableFieldInfo.getColumn());
} else {
sqlSet += SqlScriptUtils.safeParam(newPrefix + tableFieldInfo.getEl());
@ -262,7 +267,7 @@ public interface MPJBaseMethod extends Constants {
if (ignoreIf) {
return sqlSet;
}
if (AdapterHelper.getAdapter().isWithUpdateFill(tableFieldInfo)) {
if (tableFieldInfo.isWithUpdateFill()) {
// 不进行 if 包裹
return sqlSet;
}
@ -270,7 +275,7 @@ public interface MPJBaseMethod extends Constants {
}
default String mpjConvertIfProperty(String prefix, String property) {
return StrUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) + "['" + property + "']" : property;
return StringUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) + "['" + property + "']" : property;
}
default String mpjConvertIf(TableFieldInfo tableFieldInfo, final String sqlScript, final String property, final FieldStrategy fieldStrategy) {

View File

@ -0,0 +1,11 @@
package com.github.yulichang.method;
import java.io.Serializable;
/**
* result type 标识类
*
* @author yulichang
*/
public class MPJResultType implements Serializable {
}

View File

@ -27,7 +27,7 @@ public class SelectJoinCount extends MPJAbstractMethod {
SqlMethod sqlMethod = SqlMethod.SELECT_JOIN_COUNT;
String sql = String.format(sqlMethod.getSql(), sqlFirst(), sqlCount(),
mpjTableName(tableInfo), sqlAlias(), sqlFrom(), sqlWhereEntityWrapper(true, tableInfo), sqlComment());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, removeExtraWhitespaces(sql), modelClass);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addSelectMappedStatementForOther(mapperClass, sqlMethod.getMethod(), sqlSource, Long.class);
}
}

View File

@ -31,8 +31,8 @@ public class SelectJoinList extends MPJAbstractMethod {
SqlMethod sqlMethod = SqlMethod.SELECT_JOIN_LIST;
String sql = String.format(sqlMethod.getSql(), sqlFirst(), sqlDistinct(), sqlSelectColumns(tableInfo, true),
mpjTableName(tableInfo), sqlAlias(), sqlFrom(), sqlWhereEntityWrapper(true, tableInfo), mpjSqlOrderBy(tableInfo), sqlComment());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, removeExtraWhitespaces(sql), modelClass);
return this.addSelectMappedStatementForOther(mapperClass, sqlMethod.getMethod(), sqlSource, tableInfo.getEntityType());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addSelectMappedStatementForOther(mapperClass, sqlMethod.getMethod(), sqlSource, MPJResultType.class);
}
@Override

Some files were not shown because too many files have changed in this diff Show More