Merge branch 'mybatis-flex:main' into main

This commit is contained in:
farukonfly 2023-12-23 12:05:15 +08:00 committed by GitHub
commit c931e203ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
101 changed files with 2553 additions and 11300 deletions

View File

@ -7,7 +7,7 @@ body:
attributes: attributes:
label: 这个 Bug 是否已经存在: label: 这个 Bug 是否已经存在:
options: options:
- label: 我确定已经把 MyBatis-Flex 升级到最新版本 v1.7.5,并已搜索过现有的问题 (https://gitee.com/mybatis-flex/mybatis-flex/issues) - label: 我确定已经把 MyBatis-Flex 升级到最新版本 v1.7.6,并已搜索过现有的问题 (https://gitee.com/mybatis-flex/mybatis-flex/issues)
required: true required: true
- type: textarea - type: textarea
attributes: attributes:

View File

@ -13,7 +13,7 @@ body:
attributes: attributes:
label: 这个问题是否已经存在: label: 这个问题是否已经存在:
options: options:
- label: 我确定已经把 MyBatis-Flex 升级到最新版本 v1.7.5,并已搜索过现有的问题 (https://gitee.com/mybatis-flex/mybatis-flex/issues) - label: 我确定已经把 MyBatis-Flex 升级到最新版本 v1.7.6,并已搜索过现有的问题 (https://gitee.com/mybatis-flex/mybatis-flex/issues)
required: true required: true
- type: textarea - type: textarea
id: question-description id: question-description

3
.gitignore vendored
View File

@ -15,4 +15,5 @@ node_modules
yarn.lock yarn.lock
dist dist
package-lock.json package-lock.json
.flattened-pom.xml .flattened-pom.xml
/docs/.vitepress/cache/

View File

@ -2,6 +2,24 @@
查看 [全部代码贡献者](/zh/intro/what-is-mybatisflex.html#贡献者)。 查看 [全部代码贡献者](/zh/intro/what-is-mybatisflex.html#贡献者)。
## v1.7.6 20231223:
- 新增Db.selectFirstAndSecondColumnsAsMap 方法:查询结果的第一列作为 key第二列作为 value感谢 @617054137
- 新增:方言添加添加权限处理统一入口 prepareAuth感谢 @bf109f
- 优化:在数组异常时不显示数组为空异常信息的问题,感谢 @Suomm
- 优化:修改 QueryCondition 的类的相关错别字,感谢 @Suomm
- 优化:升级 MyBatis 相关依赖到最新版本,感谢 @tocken
- 修复DB2 v10.5 不支持 offset 关键字进行分页的问题,感谢 @farukonfly
- 修复DB2 v10.5 不支持 Nulls First 或 Nulls Last 语法的问题,感谢 @farukonfly
- 修复FieldWrapper 对有泛型 Entity 进行部分更新时报错的问题,感谢 @617054137
- 修复Db.updateEntitiesBatch 更新部分字段时,在某些场景下报错的问题,感谢 @617054137
- 修复:字段类型为 YearMonth,Year 等时更新出错的问题 #I8CGVM
- 修复main 方法直接调用 updateChain 方法构建 sql 时调用 toSQL 出错的问题 #I8NF9T
- 测试:优化单元测试,移除 println添加更多的断言感谢 @mofan
- 文档:添加 SpringBoot 3.2 版本启动失败解决办法,感谢 @Suomm
- 文档:优化英文文档的相关内容,感谢 @mofan
- 文档:更新 table 中的示例代码错误,感谢 @jtxfd_admin
## v1.7.5 20231124: ## v1.7.5 20231124:
- 修复:主键 ID 当传入空字符串时,调用 `insert` 方法不会依据 `@Id` 自动生成主键 id 的问题 - 修复:主键 ID 当传入空字符串时,调用 `insert` 方法不会依据 `@Id` 自动生成主键 id 的问题

View File

@ -1,13 +1,43 @@
{ {
"hash": "837c5365", "hash": "f89f5635",
"browserHash": "8541a50e", "configHash": "0e899f8e",
"lockfileHash": "2cf7bf12",
"browserHash": "f7bcbdb1",
"optimized": { "optimized": {
"vue": { "vue": {
"src": "../../../node_modules/vue/dist/vue.runtime.esm-bundler.js", "src": "../../../node_modules/vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js", "file": "vue.js",
"fileHash": "4247883c", "fileHash": "2c85f323",
"needsInterop": false
},
"vitepress > @vue/devtools-api": {
"src": "../../../node_modules/@vue/devtools-api/lib/esm/index.js",
"file": "vitepress___@vue_devtools-api.js",
"fileHash": "8af80563",
"needsInterop": false
},
"vitepress > @vueuse/integrations/useFocusTrap": {
"src": "../../../node_modules/@vueuse/integrations/useFocusTrap.mjs",
"file": "vitepress___@vueuse_integrations_useFocusTrap.js",
"fileHash": "ef0d503c",
"needsInterop": false
},
"vitepress > mark.js/src/vanilla.js": {
"src": "../../../node_modules/mark.js/src/vanilla.js",
"file": "vitepress___mark__js_src_vanilla__js.js",
"fileHash": "a227f6b7",
"needsInterop": false
},
"vitepress > minisearch": {
"src": "../../../node_modules/minisearch/dist/es/index.js",
"file": "vitepress___minisearch.js",
"fileHash": "44bd931b",
"needsInterop": false "needsInterop": false
} }
}, },
"chunks": {} "chunks": {
"chunk-7DTDMSOX": {
"file": "chunk-7DTDMSOX.js"
}
}
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -11,7 +11,9 @@ export default defineConfig({
// logo: '/assets/images/logo02.png', // logo: '/assets/images/logo02.png',
themeConfig: { themeConfig: {
outlineTitle:'章节', outline:{
label:"章节"
},
search: { search: {
provider: 'local' provider: 'local'
}, },

View File

@ -127,14 +127,14 @@ const {Layout} = DefaultTheme
src="/assets/images/ad/topiam_20230909.png" style="width: 105px;height: 50px"></a> src="/assets/images/ad/topiam_20230909.png" style="width: 105px;height: 50px"></a>
</div> </div>
<div class="banner"> <div class="banner">
以待 以待
</div> </div>
<div class="banner"> <div class="banner">
以待 以待
</div> </div>
</div> </div>
<div class="banner-bottom"> <div class="banner-bottom">
以待 以待
</div> </div>
</div> </div>
</template> </template>

View File

@ -1,4 +1,5 @@
{ {
"type": "module",
"scripts": { "scripts": {
"docs:dev": "vitepress dev", "docs:dev": "vitepress dev",
"docs:build": "vitepress build", "docs:build": "vitepress build",

View File

@ -27,6 +27,9 @@ String listsql = "select * from tb_account where age > ?"
List<Row> rows = Db.selectListBySql(listsql,18); List<Row> rows = Db.selectListBySql(listsql,18);
//查询所有大于 18 岁用户的Id和用户名对应的Map
Map map = Db.selectFirstAndSecondColumnsAsMap("select id,user_name from tb_account where age >?",18);
//分页查询:每页 10 条数据,查询第 3 页的年龄大于 18 的用户 //分页查询:每页 10 条数据,查询第 3 页的年龄大于 18 的用户
QueryWrapper query=QueryWrapper.create() QueryWrapper query=QueryWrapper.create()
.where(ACCOUNT.AGE.ge(18)); .where(ACCOUNT.AGE.ge(18));

View File

@ -2,6 +2,24 @@
查看 [全部代码贡献者](/zh/intro/what-is-mybatisflex.html#贡献者)。 查看 [全部代码贡献者](/zh/intro/what-is-mybatisflex.html#贡献者)。
## v1.7.6 20231223:
- 新增Db.selectFirstAndSecondColumnsAsMap 方法:查询结果的第一列作为 key第二列作为 value感谢 @617054137
- 新增:方言添加添加权限处理统一入口 prepareAuth感谢 @bf109f
- 优化:在数组异常时不显示数组为空异常信息的问题,感谢 @Suomm
- 优化:修改 QueryCondition 的类的相关错别字,感谢 @Suomm
- 优化:升级 MyBatis 相关依赖到最新版本,感谢 @tocken
- 修复DB2 v10.5 不支持 offset 关键字进行分页的问题,感谢 @farukonfly
- 修复DB2 v10.5 不支持 Nulls First 或 Nulls Last 语法的问题,感谢 @farukonfly
- 修复FieldWrapper 对有泛型 Entity 进行部分更新时报错的问题,感谢 @617054137
- 修复Db.updateEntitiesBatch 更新部分字段时,在某些场景下报错的问题,感谢 @617054137
- 修复:字段类型为 YearMonth,Year 等时更新出错的问题 #I8CGVM
- 修复main 方法直接调用 updateChain 方法构建 sql 时调用 toSQL 出错的问题 #I8NF9T
- 测试:优化单元测试,移除 println添加更多的断言感谢 @mofan
- 文档:添加 SpringBoot 3.2 版本启动失败解决办法,感谢 @Suomm
- 文档:优化英文文档的相关内容,感谢 @mofan
- 文档:更新 table 中的示例代码错误,感谢 @jtxfd_admin
## v1.7.5 20231124: ## v1.7.5 20231124:
- 修复:主键 ID 当传入空字符串时,调用 `insert` 方法不会依据 `@Id` 自动生成主键 id 的问题 - 修复:主键 ID 当传入空字符串时,调用 `insert` 方法不会依据 `@Id` 自动生成主键 id 的问题

View File

@ -79,3 +79,57 @@ public class MyServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
} }
``` ```
当然,在 `IService` 中,除了 `list` 方法以外,还有其他的查询方法,可能也需要复写。 当然,在 `IService` 中,除了 `list` 方法以外,还有其他的查询方法,可能也需要复写。
## 方式3使用自定义数据方言 `IDialect`
在自定义方言中,重写 `prepareAuth` 方法,根据自己的需求对 `QueryWrapper``sql`语句进行处理,添加额外条件, 以下是示例代码:
```java
public class AuthDialectImpl extends CommonsDialectImpl {
@Override
public void prepareAuth(QueryWrapper queryWrapper, OperateType operateType) {
List<QueryTable> queryTables = CPI.getQueryTables(queryWrapper);
if (queryTables == null || queryTables.isEmpty()) {
return;
}
for (QueryTable queryTable : queryTables) {
if (PROJECT.getTableName().equals(queryTable.getName())) {
queryWrapper.and(PROJECT.INSERT_USER_ID.eq(1));
}
}
super.prepareAuth(queryWrapper, operateType);
}
@Override
public void prepareAuth(String schema, String tableName, StringBuilder sql, OperateType operateType) {
if (PROJECT.getTableName().equals(tableName)) {
sql.append(AND).append(wrap("insert_user_id")).append(EQUALS).append(1);
}
super.prepareAuth(schema, tableName, sql, operateType);
}
@Override
public void prepareAuth(TableInfo tableInfo, StringBuilder sql, OperateType operateType) {
if (PROJECT.getTableName().equals(tableInfo.getTableName())) {
sql.append(AND).append(wrap("insert_user_id")).append(EQUALS).append(1);
}
super.prepareAuth(tableInfo, sql, operateType);
}
}
```
`QueryWrapper`的表做筛选可参考 **方式1**
在项目启动时通过 `DialectFactory` 注册 `AuthDialectImpl`以spring boot项目为例
```
@Configuration
public class MybatisFlexConfig implements MyBatisFlexCustomizer {
@Override
public void customize(FlexGlobalConfig flexGlobalConfig) {
// 注册查询权限监听方言
DialectFactory.registerDialect(DbType.MYSQL, new AuthDialectImpl());
}
}
```
单元测试请参考源码中的`com.mybatisflex.coretest.AuthTest`

View File

@ -161,7 +161,7 @@ public class MySetListener implements SetListener {
方法如下: 方法如下:
```java ```java
MyInsertListener insertListener = new MyInsertLister(); MyInsertListener insertListener = new MyInsertListener();
MyUpdateListener updateListener = new MyUpdateListener(); MyUpdateListener updateListener = new MyUpdateListener();
MySetListener setListener = new MySetListener(); MySetListener setListener = new MySetListener();

View File

@ -62,7 +62,7 @@ VALUES (1, '张三', 18, '2020-01-11'),
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot-starter</artifactId> <artifactId>mybatis-flex-spring-boot-starter</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>com.mysql</groupId>

View File

@ -10,7 +10,7 @@
```kotlin ```kotlin
dependencies { dependencies {
implementation("com.mybatis-flex:mybatis-flex-core:1.7.5") implementation("com.mybatis-flex:mybatis-flex-core:1.7.6")
} }
``` ```
@ -18,7 +18,7 @@ dependencies {
```groovy ```groovy
dependencies { dependencies {
implementation 'com.mybatis-flex:mybatis-flex-core:1.7.5' implementation 'com.mybatis-flex:mybatis-flex-core:1.7.6'
} }
``` ```
@ -28,7 +28,7 @@ dependencies {
```kotlin ```kotlin
dependencies { dependencies {
implementation("com.mybatis-flex:mybatis-flex-spring:1.7.5") implementation("com.mybatis-flex:mybatis-flex-spring:1.7.6")
} }
``` ```
@ -36,7 +36,7 @@ dependencies {
```groovy ```groovy
dependencies { dependencies {
implementation 'com.mybatis-flex:mybatis-flex-spring:1.7.5' implementation 'com.mybatis-flex:mybatis-flex-spring:1.7.6'
} }
``` ```
@ -46,7 +46,7 @@ dependencies {
```kotlin ```kotlin
dependencies { dependencies {
implementation("com.mybatis-flex:mybatis-flex-spring-boot-starter:1.7.5") implementation("com.mybatis-flex:mybatis-flex-spring-boot-starter:1.7.6")
} }
``` ```
@ -54,7 +54,7 @@ dependencies {
```groovy ```groovy
dependencies { dependencies {
implementation 'com.mybatis-flex:mybatis-flex-spring-boot-starter:1.7.5' implementation 'com.mybatis-flex:mybatis-flex-spring-boot-starter:1.7.6'
} }
``` ```
@ -70,7 +70,7 @@ dependencies {
```kotlin ```kotlin
dependencies { dependencies {
annotationProcessor("com.mybatis-flex:mybatis-flex-processor:1.7.5") annotationProcessor("com.mybatis-flex:mybatis-flex-processor:1.7.6")
} }
``` ```
@ -78,6 +78,6 @@ dependencies {
```groovy ```groovy
dependencies { dependencies {
annotationProcessor 'com.mybatis-flex:mybatis-flex-processor:1.7.5' annotationProcessor 'com.mybatis-flex:mybatis-flex-processor:1.7.6'
} }
``` ```

View File

@ -12,12 +12,12 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId> <artifactId>mybatis-flex-core</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId> <artifactId>mybatis-flex-processor</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
``` ```
@ -28,12 +28,12 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring</artifactId> <artifactId>mybatis-flex-spring</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId> <artifactId>mybatis-flex-processor</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
`````` ``````
@ -44,12 +44,12 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot-starter</artifactId> <artifactId>mybatis-flex-spring-boot-starter</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId> <artifactId>mybatis-flex-processor</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
``` ```
@ -72,7 +72,7 @@
<path> <path>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId> <artifactId>mybatis-flex-processor</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</path> </path>
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>

View File

@ -220,7 +220,7 @@ pom.xml 添加 `annotationProcessorPaths` 配置,
``` ```
dependencies { dependencies {
... ...
annotationProcessor 'com.mybatis-flex:mybatis-flex-processor:1.7.5' annotationProcessor 'com.mybatis-flex:mybatis-flex-processor:1.7.6'
} }
``` ```

View File

@ -10,7 +10,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-codegen</artifactId> <artifactId>mybatis-flex-codegen</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
``` ```

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -23,7 +23,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId> <artifactId>mybatis-flex-core</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>

View File

@ -92,7 +92,7 @@ public class GeneratorTest {
HikariDataSource dataSource = new HikariDataSource(); HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8"); dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8");
dataSource.setUsername("root"); dataSource.setUsername("root");
dataSource.setPassword("12345678"); dataSource.setPassword("123456");
GlobalConfig globalConfig = new GlobalConfig(); GlobalConfig globalConfig = new GlobalConfig();
@ -156,7 +156,7 @@ public class GeneratorTest {
HikariDataSource dataSource = new HikariDataSource(); HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8"); dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8");
dataSource.setUsername("root"); dataSource.setUsername("root");
dataSource.setPassword("12345678"); dataSource.setPassword("123456");
//通过 datasource globalConfig 创建代码生成器 //通过 datasource globalConfig 创建代码生成器
new Generator(dataSource, globalConfig()).generate(); new Generator(dataSource, globalConfig()).generate();
@ -232,7 +232,7 @@ public class GeneratorTest {
HikariDataSource dataSource = new HikariDataSource(); HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8"); dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8");
dataSource.setUsername("root"); dataSource.setUsername("root");
dataSource.setPassword("12345678"); dataSource.setPassword("123456");
GlobalConfig globalConfig = new GlobalConfig(); GlobalConfig globalConfig = new GlobalConfig();
@ -283,7 +283,7 @@ public class GeneratorTest {
HikariDataSource dataSource = new HikariDataSource(); HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8"); dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8");
dataSource.setUsername("root"); dataSource.setUsername("root");
dataSource.setPassword("12345678"); dataSource.setPassword("123456");
GlobalConfig globalConfig = new GlobalConfig(); GlobalConfig globalConfig = new GlobalConfig();

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -101,7 +101,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-annotation</artifactId> <artifactId>mybatis-flex-annotation</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>

View File

@ -412,7 +412,7 @@ public interface BaseMapper<T> {
*/ */
default T selectOneByMap(Map<String, Object> whereConditions) { default T selectOneByMap(Map<String, Object> whereConditions) {
FlexAssert.notEmpty(whereConditions, "whereConditions"); FlexAssert.notEmpty(whereConditions, "whereConditions");
return selectOneByQuery(QueryWrapper.create().where(whereConditions).limit(1L)); return selectOneByQuery(QueryWrapper.create().where(whereConditions));
} }
/** /**
@ -423,7 +423,7 @@ public interface BaseMapper<T> {
*/ */
default T selectOneByCondition(QueryCondition whereConditions) { default T selectOneByCondition(QueryCondition whereConditions) {
FlexAssert.notNull(whereConditions, "whereConditions"); FlexAssert.notNull(whereConditions, "whereConditions");
return selectOneByQuery(QueryWrapper.create().where(whereConditions).limit(1L)); return selectOneByQuery(QueryWrapper.create().where(whereConditions));
} }
/** /**
@ -433,6 +433,7 @@ public interface BaseMapper<T> {
* @return 实体类数据 * @return 实体类数据
*/ */
default T selectOneByQuery(QueryWrapper queryWrapper) { default T selectOneByQuery(QueryWrapper queryWrapper) {
queryWrapper.limit(1);
return MapperUtil.getSelectOneResult(selectListByQuery(queryWrapper)); return MapperUtil.getSelectOneResult(selectListByQuery(queryWrapper));
} }

View File

@ -27,7 +27,7 @@ public class FlexConsts {
} }
public static final String NAME = "MyBatis-Flex"; public static final String NAME = "MyBatis-Flex";
public static final String VERSION = "1.7.5"; public static final String VERSION = "1.7.6";
public static final String SQL = "$$sql"; public static final String SQL = "$$sql";

View File

@ -91,4 +91,32 @@ public interface IDialect {
String forSelectEntityListByIds(TableInfo tableInfo, Object[] primaryValues); String forSelectEntityListByIds(TableInfo tableInfo, Object[] primaryValues);
/**
* 权限处理
*
* @param queryWrapper queryWrapper
* @param operateType 操作类型
*/
default void prepareAuth(QueryWrapper queryWrapper, OperateType operateType) {
}
/**
* 权限处理
*
* @param schema schema
* @param tableName 表名
* @param sql sql
* @param operateType 操作类型
*/
default void prepareAuth(String schema, String tableName, StringBuilder sql, OperateType operateType) {
}
/**
* 权限处理
* @param tableInfo tableInfo
* @param sql sql
* @param operateType 操作类型
*/
default void prepareAuth(TableInfo tableInfo, StringBuilder sql, OperateType operateType) {
}
} }

View File

@ -0,0 +1,22 @@
package com.mybatisflex.core.dialect;
/**
* 操作类型
*/
public enum OperateType {
/**
* 查询
*/
SELECT,
/**
* 更新
*/
UPDATE,
/**
* 删除
*/
DELETE,
;
}

View File

@ -18,6 +18,7 @@ package com.mybatisflex.core.dialect.impl;
import com.mybatisflex.core.dialect.IDialect; import com.mybatisflex.core.dialect.IDialect;
import com.mybatisflex.core.dialect.KeywordWrap; import com.mybatisflex.core.dialect.KeywordWrap;
import com.mybatisflex.core.dialect.LimitOffsetProcessor; import com.mybatisflex.core.dialect.LimitOffsetProcessor;
import com.mybatisflex.core.dialect.OperateType;
import com.mybatisflex.core.exception.FlexExceptions; import com.mybatisflex.core.exception.FlexExceptions;
import com.mybatisflex.core.exception.locale.LocalizedFormats; import com.mybatisflex.core.exception.locale.LocalizedFormats;
import com.mybatisflex.core.logicdelete.LogicDeleteManager; import com.mybatisflex.core.logicdelete.LogicDeleteManager;
@ -164,6 +165,7 @@ public class CommonsDialectImpl implements IDialect {
} }
sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER); sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER);
} }
prepareAuth(schema, table, sql, OperateType.DELETE);
return sql.toString(); return sql.toString();
} }
@ -205,11 +207,13 @@ public class CommonsDialectImpl implements IDialect {
sql.append(wrap(primaryKeys[0])).append(EQUALS_PLACEHOLDER); sql.append(wrap(primaryKeys[0])).append(EQUALS_PLACEHOLDER);
} }
} }
prepareAuth(schema, table, sql, OperateType.DELETE);
return sql.toString(); return sql.toString();
} }
@Override @Override
public String forDeleteByQuery(QueryWrapper queryWrapper) { public String forDeleteByQuery(QueryWrapper queryWrapper) {
prepareAuth(queryWrapper, OperateType.DELETE);
return buildDeleteSql(queryWrapper); return buildDeleteSql(queryWrapper);
} }
@ -252,12 +256,13 @@ public class CommonsDialectImpl implements IDialect {
} }
sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER); sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER);
} }
prepareAuth(schema, table, sql, OperateType.UPDATE);
return sql.toString(); return sql.toString();
} }
@Override @Override
public String forUpdateByQuery(QueryWrapper queryWrapper, Row row) { public String forUpdateByQuery(QueryWrapper queryWrapper, Row row) {
prepareAuth(queryWrapper, OperateType.UPDATE);
StringBuilder sqlBuilder = new StringBuilder(); StringBuilder sqlBuilder = new StringBuilder();
Set<String> modifyAttrs = RowCPI.getModifyAttrs(row); Set<String> modifyAttrs = RowCPI.getModifyAttrs(row);
@ -332,11 +337,13 @@ public class CommonsDialectImpl implements IDialect {
} }
sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER); sql.append(wrap(primaryKeys[i])).append(EQUALS_PLACEHOLDER);
} }
prepareAuth(schema, table, sql, OperateType.SELECT);
return sql.toString(); return sql.toString();
} }
@Override @Override
public String forSelectByQuery(QueryWrapper queryWrapper) { public String forSelectByQuery(QueryWrapper queryWrapper) {
prepareAuth(queryWrapper, OperateType.SELECT);
return buildSelectSql(queryWrapper); return buildSelectSql(queryWrapper);
} }
@ -664,6 +671,7 @@ public class CommonsDialectImpl implements IDialect {
//租户ID //租户ID
tableInfo.buildTenantCondition(sql, tenantIdArgs, this); tableInfo.buildTenantCondition(sql, tenantIdArgs, this);
prepareAuth(tableInfo, sql, OperateType.DELETE);
return sql.toString(); return sql.toString();
} }
@ -723,7 +731,7 @@ public class CommonsDialectImpl implements IDialect {
sql.append(BRACKET_RIGHT).append(AND).append(buildLogicNormalCondition(logicDeleteColumn, tableInfo)); sql.append(BRACKET_RIGHT).append(AND).append(buildLogicNormalCondition(logicDeleteColumn, tableInfo));
tableInfo.buildTenantCondition(sql, tenantIdArgs, this); tableInfo.buildTenantCondition(sql, tenantIdArgs, this);
prepareAuth(tableInfo, sql, OperateType.DELETE);
return sql.toString(); return sql.toString();
} }
@ -738,6 +746,7 @@ public class CommonsDialectImpl implements IDialect {
} }
prepareAuth(queryWrapper, OperateType.DELETE);
//逻辑删除 //逻辑删除
List<QueryTable> queryTables = CPI.getQueryTables(queryWrapper); List<QueryTable> queryTables = CPI.getQueryTables(queryWrapper);
List<QueryTable> joinTables = CPI.getJoinTables(queryWrapper); List<QueryTable> joinTables = CPI.getJoinTables(queryWrapper);
@ -823,12 +832,13 @@ public class CommonsDialectImpl implements IDialect {
sql.append(AND).append(wrap(versionColumn)).append(EQUALS).append(versionValue); sql.append(AND).append(wrap(versionColumn)).append(EQUALS).append(versionValue);
} }
prepareAuth(tableInfo, sql, OperateType.UPDATE);
return sql.toString(); return sql.toString();
} }
@Override @Override
public String forUpdateEntityByQuery(TableInfo tableInfo, Object entity, boolean ignoreNulls, QueryWrapper queryWrapper) { public String forUpdateEntityByQuery(TableInfo tableInfo, Object entity, boolean ignoreNulls, QueryWrapper queryWrapper) {
prepareAuth(queryWrapper, OperateType.UPDATE);
StringBuilder sqlBuilder = new StringBuilder(); StringBuilder sqlBuilder = new StringBuilder();
Set<String> updateColumns = tableInfo.obtainUpdateColumns(entity, ignoreNulls, true); Set<String> updateColumns = tableInfo.obtainUpdateColumns(entity, ignoreNulls, true);
@ -916,7 +926,7 @@ public class CommonsDialectImpl implements IDialect {
//多租户 //多租户
Object[] tenantIdArgs = tableInfo.buildTenantIdArgs(); Object[] tenantIdArgs = tableInfo.buildTenantIdArgs();
tableInfo.buildTenantCondition(sql, tenantIdArgs, this); tableInfo.buildTenantCondition(sql, tenantIdArgs, this);
prepareAuth(tableInfo, sql, OperateType.SELECT);
return sql.toString(); return sql.toString();
} }
@ -972,7 +982,7 @@ public class CommonsDialectImpl implements IDialect {
//多租户 //多租户
tableInfo.buildTenantCondition(sql, tenantIdArgs, this); tableInfo.buildTenantCondition(sql, tenantIdArgs, this);
prepareAuth(tableInfo, sql, OperateType.SELECT);
return sql.toString(); return sql.toString();
} }

View File

@ -55,6 +55,7 @@ import java.util.*;
/** /**
* 复制于 DefaultResultSetHandler并开放若干方法方便子类重写 * 复制于 DefaultResultSetHandler并开放若干方法方便子类重写
*
* @author Clinton Begin * @author Clinton Begin
* @author Eduardo Macarron * @author Eduardo Macarron
* @author Iwao AVE! * @author Iwao AVE!
@ -290,9 +291,21 @@ public class FlexDefaultResultSetHandler extends DefaultResultSetHandler {
if (parentMapping != null) { if (parentMapping != null) {
handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping); handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
} else if (resultHandler == null) { } else if (resultHandler == null) {
DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory); if (resultMap.getId().startsWith("com.mybatisflex.core.row.RowMapper.selectFirstAndSecondColumnsAsMap")) {
handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null); ResultSet resultSet = rsw.getResultSet();
multipleResults.add(defaultResultHandler.getResultList()); skipRows(resultSet, rowBounds);
Map<Object, Object> row = new HashMap<>();
while (!resultSet.isClosed() && resultSet.next()) {
row.put(resultSet.getObject(1), resultSet.getObject(2));
}
List<Map<Object, Object>> mapArrayList = new ArrayList<>(1);
mapArrayList.add(row);
multipleResults.add(mapArrayList);
} else {
DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
multipleResults.add(defaultResultHandler.getResultList());
}
} else { } else {
handleRowValues(rsw, resultMap, resultHandler, rowBounds, null); handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
} }

View File

@ -26,6 +26,8 @@ import com.mybatisflex.core.row.RowMapper;
import com.mybatisflex.core.table.TableInfo; import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory; import com.mybatisflex.core.table.TableInfoFactory;
import com.mybatisflex.core.util.ArrayUtil; import com.mybatisflex.core.util.ArrayUtil;
import com.mybatisflex.core.util.ClassUtil;
import org.apache.ibatis.javassist.util.proxy.ProxyObject;
import java.util.*; import java.util.*;
@ -245,7 +247,7 @@ public class RowSqlProvider {
FlexAssert.notNull(entity, "entity can not be null"); FlexAssert.notNull(entity, "entity can not be null");
// Mapper 是通用 Mapper 无法通过 ProviderContext 获取直接使用 TableInfoFactory // Mapper 是通用 Mapper 无法通过 ProviderContext 获取直接使用 TableInfoFactory
TableInfo tableInfo = TableInfoFactory.ofEntityClass(entity.getClass()); TableInfo tableInfo = TableInfoFactory.ofEntityClass(ClassUtil.getUsefulClass(entity.getClass()));
// 执行 onUpdate 监听器 // 执行 onUpdate 监听器
tableInfo.invokeOnUpdateListener(entity); tableInfo.invokeOnUpdateListener(entity);

View File

@ -854,6 +854,48 @@ public class Db {
return invoker().selectObjectByQuery(null, null, queryWrapper); return invoker().selectObjectByQuery(null, null, queryWrapper);
} }
/**
* 根据 queryWrapper 查询内容数据返回为Map 第一列的值作为key 第二列的值作为value
*
* @param queryWrapper query 封装
* @return 数据内容
*/
public static Map selectFirstAndSecondColumnsAsMap(QueryWrapper queryWrapper) {
return invoker().selectFirstAndSecondColumnsAsMapByQuery(null, null, queryWrapper);
}
/**
* 查询某个内容数据返回为Map 第一列的值作为key 第二列的值作为value
*
* @param sql sql 内容
* @param args sql 参数
*/
public static Map selectFirstAndSecondColumnsAsMap(String sql, Object... args) {
return invoker().selectFirstAndSecondColumnsAsMap(sql, args);
}
/**
* 根据 queryWrapper 查询内容数据返回为Map 第一列的值作为key 第二列的值作为value
*
* @param schema 模式
* @param tableName 表名
* @param queryWrapper query 封装
* @return 数据内容
*/
public static Map selectFirstAndSecondColumnsAsMap(String schema, String tableName, QueryWrapper queryWrapper) {
return invoker().selectFirstAndSecondColumnsAsMapByQuery(schema, tableName, queryWrapper);
}
/**
* 根据 queryWrapper 查询内容数据返回为Map 第一列的值作为key 第二列的值作为value
*
* @param tableName 表名
* @param queryWrapper query 封装
* @return 数据内容
*/
public static Map selectFirstAndSecondColumnsAsMap(String tableName, QueryWrapper queryWrapper) {
return invoker().selectFirstAndSecondColumnsAsMapByQuery(null, tableName, queryWrapper);
}
/** /**
* 查询某列内容数据返回应该有 多行 1 * 查询某列内容数据返回应该有 多行 1

View File

@ -327,6 +327,12 @@ public interface RowMapper {
Object selectObject(@Param(FlexConsts.SQL) String sql, @Param(FlexConsts.SQL_ARGS) Object... args); Object selectObject(@Param(FlexConsts.SQL) String sql, @Param(FlexConsts.SQL_ARGS) Object... args);
@SelectProvider(value = RowSqlProvider.class, method = RowSqlProvider.METHOD_RAW_SQL)
Map selectFirstAndSecondColumnsAsMap(@Param(FlexConsts.SQL) String sql, @Param(FlexConsts.SQL_ARGS) Object... args);
@SelectProvider(type = RowSqlProvider.class, method = "selectListByQuery")
Map selectFirstAndSecondColumnsAsMapByQuery(@Param(FlexConsts.SCHEMA_NAME) String schema
, @Param(FlexConsts.TABLE_NAME) String tableName, @Param(FlexConsts.QUERY) QueryWrapper queryWrapper);
/** /**
* 通过 sql 查询多行数据sql 执行的结果应该只有 1 * 通过 sql 查询多行数据sql 执行的结果应该只有 1
* *
@ -453,4 +459,5 @@ public interface RowMapper {
} }
} }

View File

@ -24,6 +24,7 @@ import org.apache.ibatis.session.SqlSessionFactory;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Function; import java.util.function.Function;
@ -188,7 +189,12 @@ public class RowMapperInvoker {
public List<Row> selectAll(String schema, String tableName) { public List<Row> selectAll(String schema, String tableName) {
return execute(mapper -> mapper.selectAll(schema, tableName)); return execute(mapper -> mapper.selectAll(schema, tableName));
} }
public Map selectFirstAndSecondColumnsAsMapByQuery(String schema, String tableName, QueryWrapper queryWrapper) {
return execute(mapper -> mapper.selectFirstAndSecondColumnsAsMapByQuery(schema, tableName, queryWrapper));
}
public Map selectFirstAndSecondColumnsAsMap(String sql, Object... args) {
return execute(mapper -> mapper.selectFirstAndSecondColumnsAsMap(sql, args));
}
public Object selectObjectByQuery(String schema, String tableName, QueryWrapper queryWrapper) { public Object selectObjectByQuery(String schema, String tableName, QueryWrapper queryWrapper) {
return execute(mapper -> mapper.selectObjectByQuery(schema, tableName, queryWrapper)); return execute(mapper -> mapper.selectObjectByQuery(schema, tableName, queryWrapper));
} }

View File

@ -18,13 +18,26 @@ package com.mybatisflex.core.table;
import com.mybatisflex.core.FlexGlobalConfig; import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.mask.CompositeMaskTypeHandler; import com.mybatisflex.core.mask.CompositeMaskTypeHandler;
import com.mybatisflex.core.mask.MaskTypeHandler; import com.mybatisflex.core.mask.MaskTypeHandler;
import com.mybatisflex.core.util.ArrayUtil;
import com.mybatisflex.core.util.StringUtil; import com.mybatisflex.core.util.StringUtil;
import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.*;
import org.apache.ibatis.type.TypeHandler;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.*;
import java.time.chrono.JapaneseDate;
import java.util.Date;
public class ColumnInfo { public class ColumnInfo {
private static final Class<?>[] needGetTypeHandlerTypes = {
Date.class, java.sql.Date.class, Time.class, Timestamp.class,
Instant.class, LocalDate.class, LocalDateTime.class, LocalTime.class, OffsetDateTime.class, OffsetTime.class, ZonedDateTime.class,
Year.class, Month.class, YearMonth.class, JapaneseDate.class,
byte[].class, Byte[].class, Byte.class,
};
/** /**
* 数据库列名 * 数据库列名
*/ */
@ -132,7 +145,7 @@ public class ColumnInfo {
} }
//枚举 //枚举
else if (propertyType.isEnum()) { else if (propertyType.isEnum() || ArrayUtil.contains(needGetTypeHandlerTypes, propertyType)) {
if (configuration == null) { if (configuration == null) {
configuration = FlexGlobalConfig.getDefaultConfig().getConfiguration(); configuration = FlexGlobalConfig.getDefaultConfig().getConfiguration();
} }

View File

@ -16,6 +16,8 @@
package com.mybatisflex.core.util; package com.mybatisflex.core.util;
import org.apache.ibatis.javassist.util.proxy.ProxyObject;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -72,10 +74,13 @@ public class ClassUtil {
return getJdkProxySuperClass(clazz); return getJdkProxySuperClass(clazz);
} }
// if (ProxyObject.class.isAssignableFrom(clazz)){
// return (Class<T>) clazz.getSuperclass();
// }
//ControllerTest$ServiceTest$$EnhancerByGuice$$40471411#hello -------> Guice //ControllerTest$ServiceTest$$EnhancerByGuice$$40471411#hello -------> Guice
//com.demo.blog.Blog$$EnhancerByCGLIB$$69a17158 ----> CGLIB //com.demo.blog.Blog$$EnhancerByCGLIB$$69a17158 ----> CGLIB
//io.jboot.test.app.TestAppListener_$$_jvstb9f_0 ------> javassist //io.jboot.test.app.TestAppListener_$$_jvstb9f_0 ------> javassist
final String name = clazz.getName(); final String name = clazz.getName();
if (name.contains(ENHANCER_BY) || name.contains(JAVASSIST_BY)) { if (name.contains(ENHANCER_BY) || name.contains(JAVASSIST_BY)) {
return (Class<T>) clazz.getSuperclass(); return (Class<T>) clazz.getSuperclass();

View File

@ -105,7 +105,12 @@ public class FieldWrapper {
Type genericType = field.getGenericType(); Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) { if (genericType instanceof ParameterizedType) {
fieldWrapper.keyType = (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0]; fieldWrapper.keyType = (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
fieldWrapper.mappingType = (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[1]; Type actualTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[1];
if (actualTypeArgument instanceof ParameterizedType) {
fieldWrapper.mappingType = (Class<?>) ((ParameterizedType) actualTypeArgument).getRawType();
} else {
fieldWrapper.mappingType = (Class<?>) actualTypeArgument;
}
} }
} else { } else {
fieldWrapper.mappingType = fieldType; fieldWrapper.mappingType = fieldType;

View File

@ -32,11 +32,13 @@ public class UpdateEntity {
public static <T> T of(Class<T> clazz) { public static <T> T of(Class<T> clazz) {
clazz = ClassUtil.getUsefulClass(clazz);
return ModifyAttrsRecordProxyFactory.getInstance().get(clazz); return ModifyAttrsRecordProxyFactory.getInstance().get(clazz);
} }
public static <T> T of(Class<T> clazz, Object id) { public static <T> T of(Class<T> clazz, Object id) {
clazz = ClassUtil.getUsefulClass(clazz);
T newEntity = ModifyAttrsRecordProxyFactory.getInstance().get(clazz); T newEntity = ModifyAttrsRecordProxyFactory.getInstance().get(clazz);
TableInfo tableInfo = TableInfoFactory.ofEntityClass(clazz); TableInfo tableInfo = TableInfoFactory.ofEntityClass(clazz);
List<IdInfo> primaryKeyList = tableInfo.getPrimaryKeyList(); List<IdInfo> primaryKeyList = tableInfo.getPrimaryKeyList();

View File

@ -98,5 +98,4 @@ public class Account {
public void setDelete(Boolean delete) { public void setDelete(Boolean delete) {
isDelete = delete; isDelete = delete;
} }
} }

View File

@ -0,0 +1,97 @@
package com.mybatisflex.coretest;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DialectFactory;
import com.mybatisflex.core.dialect.IDialect;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowKey;
import com.mybatisflex.core.table.TableInfoFactory;
import com.mybatisflex.coretest.auth.AuthDialectImpl;
import com.mybatisflex.coretest.auth.Project;
import com.mybatisflex.coretest.auth.table.ProjectTableDef;
import org.junit.Before;
import org.junit.Test;
import static com.mybatisflex.coretest.auth.table.ProjectTableDef.PROJECT;
import static com.mybatisflex.coretest.table.AccountTableDef.ACCOUNT;
/**
* 权限测试
* @author zhang
* @since 2023/12/17
*/
public class AuthTest {
private IDialect dialect;
@Before
public void init() {
DialectFactory.registerDialect(DbType.MYSQL, new AuthDialectImpl());
dialect = DialectFactory.getDialect();
}
@Test
public void test() {
// 1.单个删除
assert "DELETE FROM `tb_project` WHERE `id` = ? AND `insert_user_id` = 1"
.equals(dialect.forDeleteById(PROJECT.getSchema(), PROJECT.getTableName(), new String[]{PROJECT.ID.getName()}));
// 2.批量删除
assert "DELETE FROM `tb_project` WHERE `id` = ? AND `insert_user_id` = 1"
.equals(dialect.forDeleteBatchByIds(PROJECT.getSchema(), PROJECT.getTableName(), new String[]{PROJECT.ID.getName()}, new Object[]{1L}));
// 3.查询
QueryWrapper deleteWrapper =
QueryWrapper.create(new Project()).where(PROJECT.ID.eq(1));
assert "DELETE FROM `tb_project` WHERE `id` = ? AND `insert_user_id` = ?"
.equals(dialect.forDeleteByQuery(deleteWrapper));
// 4.更新
assert "UPDATE `tb_project` SET `name` = ? WHERE `id` = ? AND `insert_user_id` = 1"
.equals(dialect.forUpdateById(PROJECT.getSchema(), PROJECT.getTableName(),
Row.ofKey(RowKey.AUTO).set(PROJECT.NAME, "项目")));
// 5.更新
Row row = new Row();
row.set(PROJECT.NAME, "项目");
QueryWrapper updateWrapper =
QueryWrapper.create(new Project()).where(PROJECT.ID.eq(1));
assert "UPDATE `tb_project` SET `name` = ? WHERE `id` = ? AND `insert_user_id` = ?"
.equals(dialect.forUpdateByQuery(updateWrapper, row));
// 6.ID查询
assert "SELECT * FROM `tb_project` WHERE `id` = ? AND `insert_user_id` = 1"
.equals(dialect.forSelectOneById(PROJECT.getSchema(), PROJECT.getTableName(), new String[]{PROJECT.ID.getName()}, new Object[]{1L}));
QueryWrapper queryWrapper = QueryWrapper.create(new Project()).where(PROJECT.ID.eq(1));
// 7.query查询
assert "SELECT `id`, `name`, `insert_user_id`, `is_delete` FROM `tb_project` WHERE `id` = ? AND `insert_user_id` = ?"
.equals(dialect.forSelectByQuery(queryWrapper));
// 8.删除
assert "UPDATE `tb_project` SET `is_delete` = 1 WHERE `id` = ? AND `is_delete` = 0 AND `insert_user_id` = 1"
.equals(dialect.forDeleteEntityById(TableInfoFactory.ofEntityClass(Project.class)));
// 9.批量删除
assert "UPDATE `tb_project` SET `is_delete` = 1 WHERE (`id` = ? ) AND `is_delete` = 0 AND `insert_user_id` = 1"
.equals(dialect.forDeleteEntityBatchByIds(TableInfoFactory.ofEntityClass(Project.class), new String[]{PROJECT.ID.getName()}));
// 10.query删除
assert "UPDATE `tb_project` SET `is_delete` = 1 WHERE `id` = ? AND `insert_user_id` = ? AND `insert_user_id` = ?"
.equals(dialect.forDeleteEntityBatchByQuery(TableInfoFactory.ofEntityClass(Project.class), queryWrapper));
// 11.更新
Project project = new Project();
project.setName("项目名称");
assert "UPDATE `tb_project` SET `name` = ? WHERE `id` = ? AND `is_delete` = 0 AND `insert_user_id` = 1"
.equals(dialect.forUpdateEntity(TableInfoFactory.ofEntityClass(Project.class), project, true));
// 12.更新
assert "UPDATE `tb_project` SET `name` = ? WHERE `id` = ? AND `insert_user_id` = ? AND `insert_user_id` = ? AND `insert_user_id` = ?"
.equals(dialect.forUpdateEntityByQuery(TableInfoFactory.ofEntityClass(Project.class), project, true, queryWrapper));
// 13.ID查询
assert "SELECT * FROM `tb_project` WHERE `id` = ? AND `is_delete` = 0 AND `insert_user_id` = 1"
.equals(dialect.forSelectOneEntityById(TableInfoFactory.ofEntityClass(Project.class)));
// 14.查询
assert "SELECT `id`, `name`, `insert_user_id`, `is_delete` FROM `tb_project` WHERE (`id` = ? ) AND `is_delete` = 0 AND `insert_user_id` = 1"
.equals(dialect.forSelectEntityListByIds(TableInfoFactory.ofEntityClass(Project.class), new String[]{PROJECT.ID.getName()}));
}
@Test
public void testWrapper() {
// (为什么打印的sql是这样的 DELETE FROM WHERE `id` = ? AND `insert_user_id` = ?)
QueryWrapper deleteWrapper =
QueryWrapper.create().where(ACCOUNT.ID.eq(1));
System.out.println(dialect.forDeleteByQuery(deleteWrapper));
}
}

View File

@ -0,0 +1,63 @@
package com.mybatisflex.coretest;
import com.mybatisflex.core.util.FieldWrapper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author tangxin
* @since 2023-12-06
*/
public class FieldWrapperTest {
public static class Demo {
private Map<String,Object> map1;
private Map<String, List<Long>> map2 ;
public Map<String, Object> getMap1() {
return map1;
}
public void setMap1(Map<String, Object> map1) {
this.map1 = map1;
}
public Map<String, List<Long>> getMap2() {
return map2;
}
public void setMap2(Map<String, List<Long>> map2) {
this.map2 = map2;
}
}
@Test
public void test01() {
try {
Map<String, List<Long>> listMap = new HashMap<>(0);
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(2L);
listMap.put("1", list);
Demo demo = new Demo();
FieldWrapper fieldWrapper1 = FieldWrapper.of(demo.getClass(), "map1");
FieldWrapper fieldWrapper2 = FieldWrapper.of(demo.getClass(), "map2");
fieldWrapper1.set(listMap, demo);
fieldWrapper2.set(listMap, demo);
Map<String, Object> map1 = (Map<String, Object>) fieldWrapper1.get(demo);
Map<String, List<Long>> map2 = (Map<String, List<Long>>) fieldWrapper1.get(demo);
System.out.println(map1.get("1"));
System.out.println(map2.get("1").get(0));
}catch (Exception e){
assert false;
}
}
}

View File

@ -0,0 +1,50 @@
package com.mybatisflex.coretest.auth;
import com.mybatisflex.core.dialect.OperateType;
import com.mybatisflex.core.dialect.impl.CommonsDialectImpl;
import com.mybatisflex.core.query.CPI;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.table.TableInfo;
import java.util.List;
import static com.mybatisflex.core.constant.SqlConsts.AND;
import static com.mybatisflex.core.constant.SqlConsts.EQUALS;
import static com.mybatisflex.coretest.auth.table.ProjectTableDef.PROJECT;
/**
* 权限处理
*/
public class AuthDialectImpl extends CommonsDialectImpl {
@Override
public void prepareAuth(QueryWrapper queryWrapper, OperateType operateType) {
List<QueryTable> queryTables = CPI.getQueryTables(queryWrapper);
if (queryTables == null || queryTables.isEmpty()) {
return;
}
for (QueryTable queryTable : queryTables) {
if (PROJECT.getTableName().equals(queryTable.getName())) {
queryWrapper.and(PROJECT.INSERT_USER_ID.eq(1));
}
}
super.prepareAuth(queryWrapper, operateType);
}
@Override
public void prepareAuth(String schema, String tableName, StringBuilder sql, OperateType operateType) {
if (PROJECT.getTableName().equals(tableName)) {
sql.append(AND).append(wrap("insert_user_id")).append(EQUALS).append(1);
}
super.prepareAuth(schema, tableName, sql, operateType);
}
@Override
public void prepareAuth(TableInfo tableInfo, StringBuilder sql, OperateType operateType) {
if (PROJECT.getTableName().equals(tableInfo.getTableName())) {
sql.append(AND).append(wrap("insert_user_id")).append(EQUALS).append(1);
}
super.prepareAuth(tableInfo, sql, operateType);
}
}

View File

@ -0,0 +1,64 @@
package com.mybatisflex.coretest.auth;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.NoneListener;
import com.mybatisflex.annotation.Table;
/**
* 权限测试类
*
* @author zhang
* @since 2023-12-17
*/
@Table(value = "tb_project", onUpdate = NoneListener.class)
public class Project {
@Id
private Long id;
/**
* 项目名称
*/
private String name;
/**
* 创建人
*/
private String insertUserId;
@Column(isLogicDelete = true)
private Boolean isDelete;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInsertUserId() {
return insertUserId;
}
public void setInsertUserId(String insertUserId) {
this.insertUserId = insertUserId;
}
public Boolean getDelete() {
return isDelete;
}
public void setDelete(Boolean delete) {
isDelete = delete;
}
}

View File

@ -6,7 +6,7 @@
<parent> <parent>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<artifactId>mybatis-flex-dependencies</artifactId> <artifactId>mybatis-flex-dependencies</artifactId>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-annotation</artifactId> <artifactId>mybatis-flex-annotation</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -23,7 +23,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring</artifactId> <artifactId>mybatis-flex-spring</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>
@ -104,7 +104,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId> <artifactId>mybatis-flex-core</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId> <artifactId>mybatis-flex-core</artifactId>
<version>1.7.5</version> <version>1.7.6</version>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -42,7 +42,6 @@ import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory; import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.ContextRefreshedEvent;
@ -91,7 +90,7 @@ import static org.springframework.util.StringUtils.tokenizeToStringArray;
* @author life * @author life
*/ */
public class FlexSqlSessionFactoryBean extends SqlSessionFactoryBean public class FlexSqlSessionFactoryBean extends SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> { implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class); private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);
@ -669,8 +668,8 @@ public class FlexSqlSessionFactoryBean extends SqlSessionFactoryBean
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public void onApplicationEvent(ApplicationEvent event) { public void onApplicationEvent(ContextRefreshedEvent event) {
if (failFast && event instanceof ContextRefreshedEvent) { if (failFast) {
// fail-fast -> check all statements are completed // fail-fast -> check all statements are completed
this.sqlSessionFactory.getConfiguration().getMappedStatementNames(); this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
} }

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>mybatis-flex-test</artifactId> <artifactId>mybatis-flex-test</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -24,7 +24,7 @@ import com.mybatisflex.core.mask.Masks;
import java.io.Serializable; import java.io.Serializable;
@Table(value = "tb_account", dataSource = "ds2", onSet = AccountOnSetListener.class) @Table(value = "tb_account6", dataSource = "ds2", onSet = AccountOnSetListener.class)
public class Account6 extends BaseEntity implements Serializable, AgeAware { public class Account6 extends BaseEntity implements Serializable, AgeAware {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -24,7 +24,7 @@ import com.mybatisflex.core.mask.Masks;
import java.io.Serializable; import java.io.Serializable;
@Table(value = "tb_account") @Table(value = "tb_account7")
public class Account7 extends BaseEntity implements Serializable, AgeAware { public class Account7 extends BaseEntity implements Serializable, AgeAware {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -22,7 +22,6 @@ public class AccountOnSetListener implements SetListener {
@Override @Override
public Object onSet(Object entity, String property, Object value) { public Object onSet(Object entity, String property, Object value) {
// System.out.println(">>>>>>> property: " + property +" value:" + value);
return value; return value;
} }

View File

@ -17,8 +17,12 @@
package com.mybatisflex.test; package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db; import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row; import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.update.UpdateWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.Configuration;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -27,7 +31,9 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @author 王帅 * @author 王帅
@ -70,4 +76,25 @@ public class DbTest {
.forEach(Assert::assertNull); .forEach(Assert::assertNull);
} }
@Test
public void test02() {
Map map = Db.selectFirstAndSecondColumnsAsMap(QueryWrapper.create().from(tb_account));
Map map2 = Db.selectFirstAndSecondColumnsAsMap("select * from tb_account");
System.out.println(map);
System.out.println(map2);
}
@Test
public void test03() {
Account account = UpdateEntity.of(Account.class,1);
account.setAge(1);
List<Account> accounts = new ArrayList<>();
accounts.add(account);
Account account2 = UpdateEntity.of(Account.class,2);
account2.setAge(2);
UpdateWrapper updateWrapper = UpdateWrapper.of(account2);
updateWrapper.setRaw("age","age+1");
accounts.add(account2);
Db.updateEntitiesBatch(accounts);
}
} }

View File

@ -17,7 +17,6 @@
package com.mybatisflex.test.relation.onetoone; package com.mybatisflex.test.relation.onetoone;
import com.mybatisflex.annotation.Id; import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.RelationManyToMany; import com.mybatisflex.annotation.RelationManyToMany;
import com.mybatisflex.annotation.Table; import com.mybatisflex.annotation.Table;
@ -28,7 +27,7 @@ import java.util.Map;
@Table(value = "tb_account") @Table(value = "tb_account")
public class Account implements Serializable { public class Account implements Serializable {
@Id(keyType = KeyType.Auto) @Id
private Long id; private Long id;
private String userName; private String userName;

View File

@ -45,7 +45,8 @@ public class AccountDTO implements Serializable {
@RelationManyToMany( @RelationManyToMany(
joinTable = "tb_role_mapping", joinTable = "tb_role_mapping",
joinSelfColumn = "account_id", joinSelfColumn = "account_id",
joinTargetColumn = "role_id" joinTargetColumn = "role_id",
selfField = "id"
) )
private List<Role> roles; private List<Role> roles;

View File

@ -1,129 +0,0 @@
/*
* Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.test.relation.onetoone;
import com.alibaba.fastjson.JSON;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.test.relation.mapper.AccountMapper;
import com.mybatisflex.test.relation.mapper.BookMapper;
import com.mybatisflex.test.relation.mapper.MenuMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
import java.util.List;
import static com.mybatisflex.test.relation.onetoone.table.MenuTableDef.MENU;
public class RelationsTester {
static AccountMapper accountMapper;
static BookMapper bookMapper;
static MenuMapper menuMapper;
@BeforeClass
public static void init() {
DataSource dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("relation/onetoone/schema.sql")
.addScript("relation/onetoone/data.sql")
.build();
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance()
.setDataSource(dataSource)
.addMapper(AccountMapper.class)
.addMapper(BookMapper.class)
.addMapper(MenuMapper.class)
.start();
//开启审计功能
AuditManager.setAuditEnable(true);
//设置 SQL 审计收集器
MessageCollector collector = new ConsoleMessageCollector();
AuditManager.setMessageCollector(collector);
accountMapper = bootstrap.getMapper(AccountMapper.class);
bookMapper = bootstrap.getMapper(BookMapper.class);
menuMapper = bootstrap.getMapper(MenuMapper.class);
}
@Test
public void testOneToOne() {
List<Account> accounts = accountMapper.selectAllWithRelations();
System.out.println(JSON.toJSONString(accounts));
}
@Test
public void testManyToOne() {
List<Book> books = bookMapper.selectAll();
System.out.println(">>>>>>1: " + books);
RelationManager.queryRelations(bookMapper, books);
System.out.println(">>>>>>2: " + books);
}
@Test
public void testManyToMany1() {
List<Account> accounts = accountMapper.selectAll();
System.out.println(">>>>>>1: " + accounts);
RelationManager.queryRelations(accountMapper, accounts);
System.out.println(">>>>>>2: " + accounts);
}
@Test
public void testAsDto() {
List<AccountDTO> accounts = accountMapper.selectListWithRelationsByQueryAs(QueryWrapper.create(), AccountDTO.class);
System.out.println(">>>>>>1: " + accounts);
}
@Test
public void testMenu() {
QueryWrapper qw = QueryWrapper.create();
qw.where(MENU.PARENT_ID.eq(0));
List<Menu> menus = menuMapper.selectListWithRelationsByQuery(qw);
System.out.println(JSON.toJSONString(menus));
}
@Test
public void testMenuIgnoreParent() {
QueryWrapper qw = QueryWrapper.create();
qw.where(MENU.PARENT_ID.eq(0));
RelationManager.addIgnoreRelations("parent");
List<Menu> menus = menuMapper.selectListWithRelationsByQuery(qw);
System.out.println(JSON.toJSONString(menus));
}
@Test
public void testPaginate() {
Page<Account> accountPage = accountMapper.paginateWithRelations(1, 2, QueryWrapper.create());
System.out.println(accountPage);
}
}

View File

@ -16,6 +16,7 @@
package com.mybatisflex.test.relation.onetoone; package com.mybatisflex.test.relation.onetoone;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.RelationManyToMany; import com.mybatisflex.annotation.RelationManyToMany;
import com.mybatisflex.annotation.Table; import com.mybatisflex.annotation.Table;
@ -25,6 +26,7 @@ import java.util.List;
@Table(value = "tb_role") @Table(value = "tb_role")
public class Role implements Serializable { public class Role implements Serializable {
@Id
private Long id; private Long id;
private String name; private String name;

View File

@ -0,0 +1,95 @@
package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.mapper.Account6Mapper;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
* @author mofan
* @date 2023/12/4 22:44
*/
public class Account6Test implements WithAssertions {
private EmbeddedDatabase dataSource;
private Account6Mapper mapper;
private static final String DATA_SOURCE_KEY = "none_key";
@BeforeClass
public static void enableAudit() {
AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
}
@Before
public void init() {
this.dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("none_key_schema.sql")
.addScript("none_key_data.sql")
.build();
MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setDataSource(DATA_SOURCE_KEY, this.dataSource)
.setLogImpl(StdOutImpl.class)
.addMapper(Account6Mapper.class)
.start();
DataSourceKey.use(DATA_SOURCE_KEY);
mapper = bootstrap.getMapper(Account6Mapper.class);
}
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
/**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I873OZ
*/
@Test
public void testGiteeIssue_I873OZ() {
Account6 account1 = new Account6();
account1.setId(3L);
account1.setUserName("michael");
account1.setAge(5);
assertThat(this.mapper.insertSelective(account1)).isEqualTo(1);
Account6 account2 = new Account6();
account2.setUserName("michael");
account2.setAge(5);
try {
mapper.insertSelective(account2);
// 没有 ID插入失败
Assert.fail();
} catch (Exception e) {
assertThat(e.getCause()).isInstanceOf(InvocationTargetException.class)
.asInstanceOf(InstanceOfAssertFactories.type(InvocationTargetException.class))
.extracting(i -> i.getTargetException().getMessage())
.asString()
.contains("NULL not allowed for column \"ID\"");
}
List<Account6> list = mapper.selectAll();
assertThat(list).hasSize(3);
}
}

View File

@ -0,0 +1,99 @@
package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.keygen.KeyGeneratorFactory;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mybatisflex.mapper.Account7Mapper;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import java.util.List;
import java.util.OptionalLong;
/**
* @author mofan
* @date 2023/12/4 23:06
*/
public class Account7Test implements WithAssertions {
private EmbeddedDatabase dataSource;
private Account7Mapper mapper;
private static final String DATA_SOURCE_KEY = "generate_key";
@BeforeClass
public static void enableAudit() {
AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
// 设置主键生成策略
KeyGeneratorFactory.register("test", new TestKeyGenerator());
}
@Before
public void init() {
this.dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("generate_key_schema.sql")
.addScript("generate_key_data.sql")
.build();
MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setDataSource(DATA_SOURCE_KEY, this.dataSource)
.setLogImpl(StdOutImpl.class)
.addMapper(Account7Mapper.class)
.start();
DataSourceKey.use(DATA_SOURCE_KEY);
mapper = bootstrap.getMapper(Account7Mapper.class);
}
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
/**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I88TX1
*/
@Test
public void testGiteeIssue_I88TX1() {
List<Account7> list = this.mapper.selectAll();
OptionalLong maxIdOpt = list.stream().mapToLong(Account7::getId).max();
if (!maxIdOpt.isPresent()) {
Assert.fail();
}
Account7 account1 = new Account7();
account1.setId(maxIdOpt.getAsLong() + 1);
account1.setUserName("michael");
account1.setAge(5);
int result1 = this.mapper.insert(account1);
assertThat(result1).isEqualTo(1);
assertThat(account1).extracting(Account7::getId).isEqualTo(3L);
Account7 account2 = new Account7();
account2.setUserName("michael");
account2.setAge(5);
int result2 = this.mapper.insert(account2);
assertThat(result2).isEqualTo(1);
assertThat(account2).extracting(Account7::getId)
.asInstanceOf(LONG)
// 组件通过时间戳 / 1000 获取
.isGreaterThanOrEqualTo(10000L);
}
}

View File

@ -18,47 +18,69 @@ package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager; import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector; import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector; import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.mapper.Account5Mapper; import com.mybatisflex.mapper.Account5Mapper;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource; public class AccountInsertWithArrayAttrTest implements WithAssertions {
public class AccountInsertWithArrayAttrTestStarter { private Account5Mapper accountMapper;
private EmbeddedDatabase dataSource;
public static void main(String[] args) { private static final String DATA_SOURCE_KEY = "data05";
DataSource dataSource = new EmbeddedDatabaseBuilder()
@BeforeClass
public static void enableAudit() {
AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
}
@Before
public void init() {
this.dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) .setType(EmbeddedDatabaseType.H2)
.addScript("schema05.sql") .addScript("schema05.sql")
.addScript("data05.sql") .addScript("data05.sql")
.build(); .build();
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance() MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setDataSource(dataSource) .setDataSource(DATA_SOURCE_KEY, dataSource)
.addMapper(Account5Mapper.class) .addMapper(Account5Mapper.class)
.start(); .start();
//开启审计功能 DataSourceKey.use(DATA_SOURCE_KEY);
AuditManager.setAuditEnable(true);
//设置 SQL 审计收集器 accountMapper = bootstrap.getMapper(Account5Mapper.class);
MessageCollector collector = new ConsoleMessageCollector(); }
AuditManager.setMessageCollector(collector);
//
// String insertSql = "INSERT INTO `tb_account`(`id`,`user_name`, `age`, `birthday`, `options`, `is_delete`, `data_scope`) VALUES (?, ?, ?, ?, ?, ?, ?)";
// Db.insertBySql(insertSql,null,"lisi",null,null,null,null,null);
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
Account5Mapper accountMapper = bootstrap.getMapper(Account5Mapper.class); @Test
@Ignore
public void testInsertWithPk() {
Account5 account = new Account5(); Account5 account = new Account5();
account.setId(3L); account.setId(3L);
account.setUserName("lisi"); account.setUserName("lisi");
account.setDataScope(new Long[]{1L, 2L}); account.setDataScope(new Long[]{1L, 2L});
accountMapper.insertWithPk(account, false); accountMapper.insertWithPk(account, false);
// todo argument type mismatch
Account5 result = accountMapper.selectOneById(3L);
assertThat(result).isNotNull()
.extracting(Account5::getUserName, Account5::getDataScope)
.containsExactly("lisi", new Long[]{1L, 2L});
} }
} }

View File

@ -19,8 +19,7 @@ import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager; import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector; import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector; import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.keygen.KeyGeneratorFactory;
import com.mybatisflex.core.mybatis.Mappers; import com.mybatisflex.core.mybatis.Mappers;
import com.mybatisflex.core.query.If; import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
@ -28,83 +27,96 @@ import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.update.UpdateChain; import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.core.update.UpdateWrapper; import com.mybatisflex.core.update.UpdateWrapper;
import com.mybatisflex.core.util.UpdateEntity; import com.mybatisflex.core.util.UpdateEntity;
import com.mybatisflex.mapper.Account6Mapper;
import com.mybatisflex.mapper.Account7Mapper;
import com.mybatisflex.mapper.ArticleMapper; import com.mybatisflex.mapper.ArticleMapper;
import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.junit.Assert; import org.assertj.core.api.WithAssertions;
import org.assertj.core.data.Index;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
import java.util.List; import java.util.List;
import java.util.Objects;
import static com.mybatisflex.test.table.AccountTableDef.ACCOUNT; import static com.mybatisflex.test.table.AccountTableDef.ACCOUNT;
import static com.mybatisflex.test.table.ArticleTableDef.ARTICLE; import static com.mybatisflex.test.table.ArticleTableDef.ARTICLE;
public class AccountTester { public class AccountNativeTest implements WithAssertions {
static AccountMapper accountMapper; private EmbeddedDatabase dataSource;
static ArticleMapper articleMapper; private AccountMapper accountMapper;
private ArticleMapper articleMapper;
private static final String DATA_SOURCE_KEY = "auto_increment";
@BeforeClass @BeforeClass
public static void init() { public static void enableAudit() {
DataSource dataSource = new EmbeddedDatabaseBuilder() AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
FlexGlobalConfig.getDefaultConfig().setLogicDeleteColumn("is_delete");
}
@Before
public void init() {
this.dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) .setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql") .addScript("auto_increment_key_schema.sql")
.addScript("data.sql") .addScript("auto_increment_key_data.sql")
.build(); .build();
FlexGlobalConfig.getDefaultConfig() MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setLogicDeleteColumn("is_delete"); .setDataSource(DATA_SOURCE_KEY, this.dataSource)
KeyGeneratorFactory.register("test", new TestKeyGenerator());
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance()
.setDataSource(dataSource)
.setLogImpl(StdOutImpl.class) .setLogImpl(StdOutImpl.class)
.addMapper(AccountMapper.class) .addMapper(AccountMapper.class)
.addMapper(Account6Mapper.class)
.addMapper(Account7Mapper.class)
.addMapper(ArticleMapper.class) .addMapper(ArticleMapper.class)
.start(); .start();
//开启审计功能 DataSourceKey.use(DATA_SOURCE_KEY);
AuditManager.setAuditEnable(true);
//设置 SQL 审计收集器
MessageCollector collector = new ConsoleMessageCollector();
AuditManager.setMessageCollector(collector);
accountMapper = bootstrap.getMapper(AccountMapper.class); accountMapper = bootstrap.getMapper(AccountMapper.class);
articleMapper = bootstrap.getMapper(ArticleMapper.class); articleMapper = bootstrap.getMapper(ArticleMapper.class);
} }
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
@Test @Test
public void testLogicDelete() { public void testLogicDelete() {
accountMapper.selectAll().forEach(System.out::println); List<Account> accounts = accountMapper.selectAll();
assertThat(accounts).hasSize(2)
.extracting(Account::getId, Account::getUserName)
.containsExactly(tuple(1L, "张*"), tuple(2L, "王麻**叔"));
} }
@Test @Test
public void testExecutor() { public void testExecutor() {
DbChain.table("tb_account") List<Account> accountList = DbChain.table("tb_account")
.select(ACCOUNT.ALL_COLUMNS) .select(ACCOUNT.ALL_COLUMNS)
.from(ACCOUNT) .from(ACCOUNT)
.where(ACCOUNT.ID.ge(1)) .where(ACCOUNT.ID.ge(1))
.listAs(Account.class) .listAs(Account.class);
.forEach(System.out::println); assertThat(accountList).hasSize(2)
.extracting(Account::getId, Account::getUserName)
.containsExactly(tuple(1L, "张*"), tuple(2L, "王麻**叔"));
AccountMapper accountBaseMapper = (AccountMapper) Mappers.ofEntityClass(Account.class); AccountMapper accountBaseMapper = (AccountMapper) Mappers.ofEntityClass(Account.class);
AccountMapper accountMapper = Mappers.ofMapperClass(AccountMapper.class); AccountMapper accountMapper = Mappers.ofMapperClass(AccountMapper.class);
System.out.println(">>>>> : " + (accountBaseMapper == accountMapper)); assertThat(accountBaseMapper).isSameAs(accountMapper);
Account account = accountBaseMapper.selectOneById(1); Account account = accountBaseMapper.selectOneById(1);
System.out.println(">>>> account: " + account); assertThat(account).isNotNull()
.extracting(Account::getId, Account::getUserName)
.containsExactly(1L, "张*");
} }
@Test @Test
@ -113,15 +125,19 @@ public class AccountTester {
queryWrapper.where(Account::getId).ge(100) queryWrapper.where(Account::getId).ge(100)
.and(Account::getUserName).like("michael") .and(Account::getUserName).like("michael")
.or(Account::getUserName).like(null, If::notNull); .or(Account::getUserName).like(null, If::notNull);
System.out.println(queryWrapper.toSQL()); String expectSql = "SELECT * FROM WHERE `id` >= 100 AND `user_name` LIKE '%michael%'";
assertThat(queryWrapper.toSQL()).isEqualTo(expectSql);
} }
@Test @Test
public void testTenant() { public void testTenant() {
QueryWrapper queryWrapper = QueryWrapper.create(); QueryWrapper queryWrapper = QueryWrapper.create();
// id >= 1
queryWrapper.where(Account::getId).ge(1); queryWrapper.where(Account::getId).ge(1);
List<Account> accounts = accountMapper.selectListByQuery(queryWrapper); List<Account> accounts = accountMapper.selectListByQuery(queryWrapper);
System.out.println(accounts); assertThat(accounts).hasSize(2)
.extracting(Account::getId, Account::getUserName)
.containsExactly(tuple(1L, "张*"), tuple(2L, "王麻**叔"));
} }
@Test @Test
@ -130,38 +146,56 @@ public class AccountTester {
queryWrapper.from(ARTICLE) queryWrapper.from(ARTICLE)
.leftJoin(ACCOUNT).on(ARTICLE.ACCOUNT_ID.eq(ACCOUNT.ID)) .leftJoin(ACCOUNT).on(ARTICLE.ACCOUNT_ID.eq(ACCOUNT.ID))
.where(ARTICLE.ID.ge(1)); .where(ARTICLE.ID.ge(1));
String expectSql = "SELECT * FROM `tb_article` " +
"LEFT JOIN `tb_account` ON `tb_article`.`account_id` = `tb_account`.`id` " +
"WHERE `tb_article`.`id` >= 1";
assertThat(queryWrapper.toSQL()).isEqualTo(expectSql);
List<Article> accounts = articleMapper.selectListByQuery(queryWrapper); List<Article> accounts = articleMapper.selectListByQuery(queryWrapper);
System.out.println(accounts); assertThat(accounts).hasSize(3)
.extracting(Article::getId, Article::getAccountId, Article::getTitle)
.containsExactly(tuple(1L, 1L, "标题1"), tuple(2L, 2L, "标题2"), tuple(3L, 1L, "标题3"));
} }
/** /**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7QD29 * issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7QD29
*/ */
@Test @Test
public void testLeftJoinSelfForLogicDelete() { public void testGiteeIssue_I7QD29() {
QueryWrapper queryWrapper = QueryWrapper.create(); QueryWrapper queryWrapper = QueryWrapper.create();
queryWrapper.from(ACCOUNT) queryWrapper.from(ACCOUNT)
.leftJoin(ACCOUNT).as("a1").on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID)) .leftJoin(ARTICLE).as("a1").on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID))
.leftJoin(ACCOUNT).as("a2").on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID)) .leftJoin(ARTICLE).as("a2").on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID))
.where(ACCOUNT.ID.ge(1)); .where(ACCOUNT.ID.ge(1));
List<Article> accounts = articleMapper.selectListByQuery(queryWrapper); List<Article> accounts = articleMapper.selectListByQuery(queryWrapper);
System.out.println(accounts); String expectSql = "SELECT * FROM `tb_account` " +
"LEFT JOIN `tb_article` AS `a1` ON `tb_account`.`id` = `a1`.`account_id` AND `a1`.`is_delete` = 0 " +
"LEFT JOIN `tb_article` AS `a2` ON `tb_account`.`id` = `a1`.`account_id` AND `a2`.`is_delete` = 0 " +
"WHERE `tb_account`.`id` >= 1";
assertThat(queryWrapper.toSQL()).isEqualTo(expectSql);
assertThat(accounts).hasSize(9);
} }
/** /**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7VAG8 * issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7VAG8
*/ */
@Test @Test
public void testLeftJoinSelectWithIgnoreColumn() { public void testGiteeIssue_I7VAG8() {
QueryWrapper queryWrapper = QueryWrapper.create(); QueryWrapper queryWrapper = QueryWrapper.create();
queryWrapper queryWrapper
.select(ACCOUNT.ID, ACCOUNT.AGE, ARTICLE.TITLE) .select(ACCOUNT.ID, ACCOUNT.AGE, ARTICLE.TITLE)
.from(ACCOUNT) .from(ACCOUNT)
.leftJoin(ARTICLE).on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID)) .leftJoin(ARTICLE).on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID))
.where(ACCOUNT.ID.ge(1)); .where(ACCOUNT.ID.ge(1));
String expectSql = "SELECT `tb_account`.`id` AS `account_id`, `tb_account`.`age` AS `my_age`, `tb_article`.`title` " +
"FROM `tb_account` " +
"LEFT JOIN `tb_article` " +
"ON `tb_account`.`id` = `tb_article`.`account_id` " +
"WHERE `tb_account`.`id` >= 1";
assertThat(queryWrapper.toSQL()).isEqualTo(expectSql);
List<Account> accounts = accountMapper.selectListByQuery(queryWrapper); List<Account> accounts = accountMapper.selectListByQuery(queryWrapper);
System.out.println(accounts); assertThat(accounts).hasSize(2)
.extracting(Account::getId, Account::getAge, Account::getTitle)
.containsExactly(tuple(1L, 18, "标题1"), tuple(2L, 19, "标题2"));
} }
@ -169,15 +203,17 @@ public class AccountTester {
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7RE0J * issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I7RE0J
*/ */
@Test @Test
public void testUpdateByUpdateWrapper() { @Ignore
public void testGiteeIssue_I7RE0J() {
Account account = new Account(); Account account = new Account();
account.setId(1L); account.setId(1L);
account = UpdateWrapper.of(account) account = UpdateWrapper.of(account)
.set(Account::getId, 1) .set(Account::getId, 1)
.set(Account::getAge, 20) .set(Account::getAge, 20)
//设置 Ignore 字段会被自动忽略 // 设置 Ignore 字段会被自动忽略
.setRaw(Account::getTitle, "xxxx") .setRaw(Account::getTitle, "xxxx")
.toEntity(); .toEntity();
// todo title not found
accountMapper.update(account); accountMapper.update(account);
} }
@ -185,19 +221,27 @@ public class AccountTester {
@Test @Test
public void testSelectAsToDTO() { public void testSelectAsToDTO() {
QueryWrapper queryWrapper = QueryWrapper.create(); QueryWrapper queryWrapper = QueryWrapper.create();
// queryWrapper.select(ACCOUNT.ALL_COLUMNS,ARTICLE.TITLE.as(AccountDTO::getPermissions))
queryWrapper.select(ACCOUNT.ALL_COLUMNS, ACCOUNT.USER_NAME.as(AccountDTO::getTestOtherField)) queryWrapper.select(ACCOUNT.ALL_COLUMNS, ACCOUNT.USER_NAME.as(AccountDTO::getTestOtherField))
// queryWrapper.select(ACCOUNT.ALL_COLUMNS) .from(ACCOUNT)
.from(ACCOUNT).leftJoin(ARTICLE).on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID)); .leftJoin(ARTICLE).on(ACCOUNT.ID.eq(ARTICLE.ACCOUNT_ID));
String expectSql = "SELECT `tb_account`.*, `tb_account`.`user_name` AS `test_other_field` " +
"FROM `tb_account` " +
"LEFT JOIN `tb_article` " +
"ON `tb_account`.`id` = `tb_article`.`account_id`";
assertThat(queryWrapper.toSQL()).isEqualTo(expectSql);
List<AccountDTO> accountDTOS = accountMapper.selectListByQueryAs(queryWrapper, AccountDTO.class); List<AccountDTO> accountDTOS = accountMapper.selectListByQueryAs(queryWrapper, AccountDTO.class);
System.out.println(accountDTOS); assertThat(accountDTOS).hasSize(2)
.extracting(AccountDTO::getId, AccountDTO::getUserName)
.containsExactly(tuple(1L, "张*"), tuple(2L, "王麻**叔"));
} }
@Test @Test
public void testUpdate1() { public void testUpdate1() {
List<Account> accounts = accountMapper.selectAll(); List<Account> accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(2)
.extracting(Account::getId, Account::getAge)
.containsExactly(tuple(1L, 18), tuple(2L, 19));
Account account = UpdateEntity.of(Account.class, 1); Account account = UpdateEntity.of(Account.class, 1);
@ -209,46 +253,54 @@ public class AccountTester {
accounts = accountMapper.selectAll(); accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(2)
.filteredOn(i -> Objects.equals(1L, i.getId()))
.extracting(Account::getUserName, Account::getAge)
.containsExactly(tuple("**si", 19));
} }
@Test @Test
public void testUpdate2() { public void testUpdate2() {
List<Account> accounts = accountMapper.selectAll(); List<Account> accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(2)
.filteredOn(i -> Objects.equals(1L, i.getId()))
.extracting(Account::getUserName)
.containsExactly("张*");
UpdateChain.of(Account.class) UpdateChain.of(Account.class)
.set(Account::getUserName, "zhangsan123") .set(Account::getUserName, "zhangsan123")
// .leftJoin(ARTICLE).on(ARTICLE.ACCOUNT_ID.eq(ACCOUNT.ID))
.where(Account::getId).eq(1) .where(Account::getId).eq(1)
// .and(ARTICLE.ID.ge(0))
.limit(1) .limit(1)
.remove(); .remove();
accounts = accountMapper.selectAll(); accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(1)
.singleElement()
.extracting(Account::getId, Account::getUserName)
.containsExactly(2L, "王麻**叔");
} }
/** /**
* https://gitee.com/mybatis-flex/mybatis-flex/issues/I7L6DF * https://gitee.com/mybatis-flex/mybatis-flex/issues/I7L6DF
*/ */
@Test @Test
public void testInsertSelectiveWithPk() { public void testGiteeIssue_I7L6DF() {
List<Account> accounts = accountMapper.selectAll(); List<Account> accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(2);
Account account = new Account(); Account account = new Account();
account.setId(4L); account.setId(4L);
account.setUserName("test04"); account.setUserName("test04");
int rows = accountMapper.insertSelectiveWithPk(account); int rows = accountMapper.insertSelectiveWithPk(account);
System.out.println(rows); assertThat(rows).isEqualTo(1);
accounts = accountMapper.selectAll(); accounts = accountMapper.selectAll();
System.out.println(accounts); assertThat(accounts).hasSize(3)
.filteredOn(i -> Objects.equals(4L, i.getId()))
.extracting(Account::getUserName)
.containsExactly("te***4");
} }
@ -258,65 +310,14 @@ public class AccountTester {
account.setUserName("michael"); account.setUserName("michael");
Account newAccount = UpdateWrapper.of(account) Account newAccount = UpdateWrapper.of(account)
// .setRaw("birthday", "now()")
// .setRaw(ACCOUNT.BIRTHDAY, "now()")
.setRaw(Account::getBirthday, "now()") .setRaw(Account::getBirthday, "now()")
.toEntity(); .toEntity();
accountMapper.insert(newAccount); accountMapper.insert(newAccount);
Account result = accountMapper.selectOneByEntityId(newAccount);
assertThat(result).isNotNull()
.extracting(Account::getId, Account::getUserName, Account::getBirthday)
.contains(3L, Index.atIndex(0))
.contains("mi****l", Index.atIndex(1))
.allMatch(Objects::nonNull);
} }
/**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I873OZ
*/
@Test
public void testInsertSelective01() {
Account6Mapper mapper = MybatisFlexBootstrap.getInstance()
.getMapper(Account6Mapper.class);
Account6 account1 = new Account6();
account1.setId(1L);
account1.setUserName("michael");
account1.setAge(5);
Assert.assertEquals(mapper.insertSelective(account1), 1);
Account6 account2 = new Account6();
// account2.setId(1L); 不设置主键
account2.setUserName("michael");
account2.setAge(5);
Assert.assertEquals(mapper.insertSelective(account2), 1);
}
/**
* issues https://gitee.com/mybatis-flex/mybatis-flex/issues/I88TX1
*/
@Test
public void testInsertWithEntityId() {
Account7Mapper mapper = MybatisFlexBootstrap.getInstance()
.getMapper(Account7Mapper.class);
Account7 account1 = new Account7();
account1.setId(1L);
account1.setUserName("michael");
account1.setAge(5);
int result1 = mapper.insert(account1);
Assert.assertEquals(result1, 1);
Account7 account2 = new Account7();
// account2.setId(1L); 不设置主键自动生成主键
account2.setUserName("michael");
account2.setAge(5);
int result2 = mapper.insert(account2);
Assert.assertEquals(result2, 1);
}
} }

View File

@ -16,19 +16,23 @@
package com.mybatisflex.test; package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager; import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector; import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.row.DbChain; import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row; import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowKey; import com.mybatisflex.core.row.RowKey;
import com.mybatisflex.core.row.RowUtil; import lombok.SneakyThrows;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource; import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -36,73 +40,102 @@ import java.util.List;
* @author 王帅 * @author 王帅
* @since 2023-07-23 * @since 2023-07-23
*/ */
public class DbChainTest { public class DbChainTest implements WithAssertions {
private static final String[] PROPERTIES = new String[]{"ID", "USER_NAME", "AGE", "BIRTHDAY"};
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final String ENVIRONMENT_ID = "db_chain";
private EmbeddedDatabase database;
@BeforeClass @BeforeClass
public static void init() { public static void enableAudit() {
DataSource dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.addScript("data.sql")
.build();
MybatisFlexBootstrap.getInstance()
.setDataSource(dataSource)
.start();
AuditManager.setAuditEnable(true); AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector()); AuditManager.setMessageCollector(new ConsoleMessageCollector());
} }
@Before
public void init() {
this.database = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("auto_increment_key_schema.sql")
.addScript("auto_increment_key_data.sql")
.build();
// Environment environment = new Environment(ENVIRONMENT_ID, new JdbcTransactionFactory(), this.database);
// FlexConfiguration configuration = new FlexConfiguration(environment);
// configuration.addMapper(RowMapper.class);
// FlexGlobalConfig flexGlobalConfig = new FlexGlobalConfig();
// flexGlobalConfig.setConfiguration(configuration);
// flexGlobalConfig.setSqlSessionFactory(new DefaultSqlSessionFactory(configuration));
// FlexGlobalConfig.setConfig(environment.getId(), flexGlobalConfig, false);
}
@After
public void destroy() {
// 用一个销毁一个保证每个测试方法的都是一个新的
this.database.shutdown();
}
@Test @Test
public void testSave() { public void testSave() {
Date birthday = new Date();
boolean saved = DbChain.table("tb_account") boolean saved = DbChain.table("tb_account")
.setId(RowKey.AUTO) .setId(RowKey.AUTO)
.set("user_name", "王帅") .set("user_name", "王帅")
.set("age", 18) .set("age", 18)
.set("birthday", new Date()) .set("birthday", birthday)
.save(); .save();
assertThat(saved).isTrue();
Row row = DbChain.table("tb_account") Row row = DbChain.table("tb_account")
.where("user_name = ?", "王帅") .where("user_name = ?", "王帅")
.one(); .one();
System.out.println(row); assertThat(row).extracting(PROPERTIES)
.containsExactly(3, "王帅", 18, new Timestamp(birthday.getTime()));
} }
@Test @Test
@SneakyThrows
public void testUpdate() { public void testUpdate() {
boolean updated = DbChain.table("tb_account") boolean updated = DbChain.table("tb_account")
.setId(RowKey.AUTO, 1) .setId(RowKey.AUTO, 1)
.set("age", 1000) .set("age", 1000)
.updateById(); .updateById();
assertThat(updated).isTrue();
Row row = DbChain.table("tb_account") Row row = DbChain.table("tb_account")
.where("id = ?", 1) .where("id = ?", 1)
.one(); .one();
System.out.println(row); Date date = DATE_FORMAT.parse("2020-01-11");
assertThat(row).extracting(PROPERTIES)
.containsExactly(1, "张三", 1000, new Timestamp(date.getTime()));
} }
@Test @Test
@SneakyThrows
public void testRemove() { public void testRemove() {
DbChain.table("tb_account") DbChain.table("tb_account")
.where("id = ?", 1) .where("id = ?", 1)
.remove(); .remove();
long count = DbChain.table("tb_account").count(); long count = DbChain.table("tb_account").count();
assertThat(count).isEqualTo(1L);
List<Row> tb_account = DbChain.table("tb_account").list(); List<Row> tb_account = DbChain.table("tb_account").list();
RowUtil.printPretty(tb_account);
System.out.println(">>>>>>testRemove count: " + count); assertThat(tb_account).hasSize(1)
.extracting(PROPERTIES)
.containsExactly(tuple(2, "王麻子叔叔", 19, new Timestamp(DATE_FORMAT.parse("2021-03-21").getTime())));
} }
@Test @Test
public void testList() { public void testList() {
DbChain.table("tb_account") List<Row> list = DbChain.table("tb_account").list();
.list() assertThat(list).hasSize(2)
.forEach(System.out::println); .extracting("ID", "USER_NAME")
.containsExactly(tuple(1, "张三"), tuple(2, "王麻子叔叔"));
} }
} }

View File

@ -18,12 +18,16 @@ package com.mybatisflex.test;
import com.mybatisflex.core.FlexGlobalConfig; import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.datasource.DataSourceKey;
import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.assertj.core.api.WithAssertions; import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
import java.util.Date; import java.util.Date;
/** /**
@ -34,33 +38,51 @@ import java.util.Date;
*/ */
public class ListenerTest implements WithAssertions { public class ListenerTest implements WithAssertions {
// 注册父类接口监听器 private static final String DATA_SOURCE_KEY = "listener";
// @Test
public void onInsertInterface() throws Exception { private AccountMapper accountMapper;
DataSource dataSource = new EmbeddedDatabaseBuilder() private EmbeddedDatabase dataSource;
@Before
public void init() {
dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) .setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql") .addScript("auto_increment_key_schema.sql")
.build(); .build();
// 注册全局监听器 // 注册全局监听器
FlexGlobalConfig defaultConfig = FlexGlobalConfig.getDefaultConfig(); FlexGlobalConfig defaultConfig = FlexGlobalConfig.getDefaultConfig();
// age < 0将其设置为 0
defaultConfig.registerInsertListener(new AgeHandleListener(), AgeAware.class); defaultConfig.registerInsertListener(new AgeHandleListener(), AgeAware.class);
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance() MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setLogImpl(StdOutImpl.class) .setLogImpl(StdOutImpl.class)
.setDataSource(dataSource) .setDataSource(DATA_SOURCE_KEY, dataSource)
.addMapper(AccountMapper.class) .addMapper(AccountMapper.class)
.start(); .start();
AccountMapper accountMapper = bootstrap.getMapper(AccountMapper.class); DataSourceKey.use(DATA_SOURCE_KEY);
accountMapper = bootstrap.getMapper(AccountMapper.class);
}
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
@Test
public void onInsertInterface() {
Account account = new Account(); Account account = new Account();
account.setAge(-2); account.setAge(-2);
account.setUserName("on insert"); account.setUserName("on insert");
account.setBirthday(new Date()); Date birthday = new Date();
account.setBirthday(birthday);
accountMapper.insert(account); accountMapper.insert(account);
Account one = accountMapper.selectOneById(account.getId()); Account one = accountMapper.selectOneById(account.getId());
System.out.println(one); assertThat(one).isNotNull()
// assertThat(one.getAge()).isEqualTo(1); .extracting(Account::getId, Account::getUserName, Account::getAge, Account::getBirthday)
.containsExactly(1L, "on******t", 0, birthday);
} }
} }

View File

@ -0,0 +1,173 @@
/*
* Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.test;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.test.relation.mapper.AccountMapper;
import com.mybatisflex.test.relation.mapper.BookMapper;
import com.mybatisflex.test.relation.mapper.MenuMapper;
import com.mybatisflex.test.relation.onetoone.Account;
import com.mybatisflex.test.relation.onetoone.AccountDTO;
import com.mybatisflex.test.relation.onetoone.Book;
import com.mybatisflex.test.relation.onetoone.Menu;
import lombok.SneakyThrows;
import net.javacrumbs.jsonunit.assertj.JsonAssertions;
import org.apache.commons.io.FileUtils;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static com.mybatisflex.test.relation.onetoone.table.MenuTableDef.MENU;
public class RelationsTest implements WithAssertions {
private AccountMapper accountMapper;
private BookMapper bookMapper;
private MenuMapper menuMapper;
private EmbeddedDatabase dataSource;
private static final String DATA_SOURCE_KEY = "relation-onetoone";
private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build();
@BeforeClass
public static void enableAudit() {
AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
}
@Before
public void init() {
dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("relation/onetoone/schema.sql")
.addScript("relation/onetoone/data.sql")
.build();
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance()
.setDataSource(DATA_SOURCE_KEY, dataSource)
.addMapper(AccountMapper.class)
.addMapper(BookMapper.class)
.addMapper(MenuMapper.class)
.start();
DataSourceKey.use(DATA_SOURCE_KEY);
accountMapper = bootstrap.getMapper(AccountMapper.class);
bookMapper = bootstrap.getMapper(BookMapper.class);
menuMapper = bootstrap.getMapper(MenuMapper.class);
}
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
@Test
@SneakyThrows
public void testOneToOne() {
List<com.mybatisflex.test.relation.onetoone.Account> accounts = accountMapper.selectAllWithRelations();
assertThat(accounts).hasSize(5);
assertRelationResult(accounts, "relation/result/account-relation-result.json");
}
@Test
public void testManyToOne() {
List<Book> books = bookMapper.selectAll();
assertThat(books).hasSize(6)
.extracting(Book::getId)
.containsExactly(1L, 2L, 3L, 4L, 5L, 6L);
RelationManager.queryRelations(bookMapper, books);
assertRelationResult(books, "relation/result/book-relation-result.json");
}
@Test
public void testManyToMany1() {
List<com.mybatisflex.test.relation.onetoone.Account> accounts = accountMapper.selectAll();
assertThat(accounts).hasSize(5)
.extracting(Account::getId)
.containsExactly(1L, 2L, 3L, 4L, 5L);
RelationManager.queryRelations(accountMapper, accounts);
assertRelationResult(accounts, "relation/result/account-relation-result.json");
}
@Test
public void testAsDto() {
List<com.mybatisflex.test.relation.onetoone.AccountDTO> accounts = accountMapper.selectListWithRelationsByQueryAs(QueryWrapper.create(), AccountDTO.class);
assertRelationResult(accounts, "relation/result/accountDto-relation-result.json");
}
@Test
public void testMenu() {
QueryWrapper qw = QueryWrapper.create();
qw.where(MENU.PARENT_ID.eq(0));
List<Menu> menus = menuMapper.selectListWithRelationsByQuery(qw);
assertRelationResult(menus, "relation/result/menu-relation-result.json");
}
@Test
public void testMenuIgnoreParent() {
QueryWrapper qw = QueryWrapper.create();
qw.where(MENU.PARENT_ID.eq(0));
RelationManager.addIgnoreRelations("parent");
List<Menu> menus = menuMapper.selectListWithRelationsByQuery(qw);
assertRelationResult(menus, "relation/result/menu-relation-ignore-parent-result.json");
}
@Test
public void testPaginate() {
Page<Account> accountPage = accountMapper.paginateWithRelations(1, 2, QueryWrapper.create());
assertRelationResult(accountPage.getRecords(), "relation/result/account-page-relation-result.json");
}
private void assertRelationResult(Object object, String classPath) {
String resultJson = writeObject2String(object);
String expectJson = getFileAsString(classPath);
JsonAssertions.assertThatJson(resultJson).isEqualTo(expectJson);
}
@SneakyThrows
private String writeObject2String(Object object) {
return JSON_MAPPER.writeValueAsString(object);
}
@SneakyThrows
private String getFileAsString(String classPath) {
ClassPathResource resource = new ClassPathResource(classPath);
return FileUtils.readFileToString(resource.getFile(), StandardCharsets.UTF_8);
}
}

View File

@ -19,76 +19,104 @@ import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager; import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector; import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.keygen.KeyGenerators; import com.mybatisflex.core.keygen.KeyGenerators;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db; import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row; import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowKey; import com.mybatisflex.core.row.RowKey;
import com.mybatisflex.core.row.RowUtil;
import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource;
import java.util.List; import java.util.List;
import static com.mybatisflex.test.relation.onetoone.table.AccountTableDef.ACCOUNT; import static com.mybatisflex.test.relation.onetoone.table.AccountTableDef.ACCOUNT;
public class RowTestStarter { public class RowTest implements WithAssertions {
private static final String DATA_SOURCE_KEY = "row";
private EmbeddedDatabase dataSource;
@BeforeClass @BeforeClass
public static void init() { public static void enableAudit() {
DataSource dataSource = new EmbeddedDatabaseBuilder() AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
}
@Before
public void init() {
dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) .setType(EmbeddedDatabaseType.H2)
.addScript("schema_row.sql") .addScript("schema_row.sql")
.addScript("data_row.sql") .addScript("data_row.sql")
.build(); .build();
MybatisFlexBootstrap.getInstance() new MybatisFlexBootstrap().setDataSource(DATA_SOURCE_KEY, dataSource)
.setDataSource(dataSource)
.setLogImpl(StdOutImpl.class) .setLogImpl(StdOutImpl.class)
.start(); .start();
AuditManager.setAuditEnable(true); DataSourceKey.use(DATA_SOURCE_KEY);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
} }
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
}
@Test @Test
public void testSetRaw(){ public void testSetRaw() {
Row row = new Row(); Row row = new Row();
row.set("user_name","michael"); row.set("user_name", "michael");
row.setRaw("birthday","now()"); row.setRaw("birthday", "now()");
Db.insert("tb_account",row); Db.insert("tb_account", row);
List<Row> rowList = Db.selectAll("tb_account"); List<Row> rowList = Db.selectAll("tb_account");
RowUtil.printPretty(rowList); assertThat(rowList).hasSize(3)
.extracting("USER_NAME")
.containsOnly("张三", "王麻子叔叔", "michael");
// 插入的数据没有 id
assertThat(row).doesNotContainKey("id");
} }
@Test @Test
public void testCustomRowKey(){ public void testCustomRowKey() {
RowKey rowKey = RowKey.of("id", KeyType.Generator, KeyGenerators.flexId); RowKey rowKey = RowKey.of("id", KeyType.Generator, KeyGenerators.flexId);
Row row = Row.ofKey(rowKey); Row row = Row.ofKey(rowKey);
row.set("user_name","michael"); row.set("user_name", "michael");
row.setRaw("birthday","now()"); row.setRaw("birthday", "now()");
Db.insert("tb_account",row); Db.insert("tb_account", row);
List<Row> rowList = Db.selectAll("tb_account"); List<Row> rowList = Db.selectAll("tb_account");
RowUtil.printPretty(rowList); assertThat(rowList).hasSize(3)
.extracting("USER_NAME")
.containsOnly("张三", "王麻子叔叔", "michael");
// 指定了主键生成策略 ID
assertThat(row).containsKey("id")
.extracting("id")
.isInstanceOf(Long.class);
} }
//https://gitee.com/mybatis-flex/mybatis-flex/issues/I7W7HQ // https://gitee.com/mybatis-flex/mybatis-flex/issues/I7W7HQ
@Test @Test
public void testRow01(){ public void testGiteeIssue_I7W7HQ() {
QueryWrapper qw = QueryWrapper.create().select("id, MAX(`tb_account`.`age`)") QueryWrapper qw = QueryWrapper.create().select("id, MAX(`tb_account`.`age`)")
.groupBy("id") .groupBy("id")
.from(ACCOUNT); .from(ACCOUNT);
List<Row> rowList = Db.selectListByQuery(qw); List<Row> rowList = Db.selectListByQuery(qw);
RowUtil.printPretty(rowList); assertThat(rowList).hasSize(2)
.extracting("MAX(TB_ACCOUNT.AGE)")
.containsOnly(18, 19);
} }
} }

View File

@ -19,50 +19,66 @@ package com.mybatisflex.test;
import com.mybatisflex.core.MybatisFlexBootstrap; import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager; import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector; import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector; import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryChain; import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.update.UpdateChain; import com.mybatisflex.core.update.UpdateChain;
import lombok.SneakyThrows;
import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.assertj.core.api.WithAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import javax.sql.DataSource; import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import static com.mybatisflex.test.table.AccountTableDef.ACCOUNT; import static com.mybatisflex.test.table.AccountTableDef.ACCOUNT;
import static com.mybatisflex.test.table.ArticleTableDef.ARTICLE; import static com.mybatisflex.test.table.ArticleTableDef.ARTICLE;
public class UpdateChainTest { public class UpdateChainTest implements WithAssertions {
static AccountMapper accountMapper; private AccountMapper accountMapper;
private EmbeddedDatabase dataSource;
private static final String DATA_SOURCE_KEY = "ds2";
@BeforeClass @BeforeClass
public static void init() { public static void enableAudit() {
DataSource dataSource = new EmbeddedDatabaseBuilder() AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(new ConsoleMessageCollector());
}
@Before
public void init() {
this.dataSource = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) .setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql") .addScript("schema.sql")
.addScript("data.sql") .addScript("data.sql")
.build(); .build();
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance() MybatisFlexBootstrap bootstrap = new MybatisFlexBootstrap()
.setDataSource(dataSource) .setDataSource(DATA_SOURCE_KEY, this.dataSource)
.setLogImpl(StdOutImpl.class) .setLogImpl(StdOutImpl.class)
.addMapper(AccountMapper.class) .addMapper(AccountMapper.class)
.start(); .start();
//开启审计功能 DataSourceKey.use(DATA_SOURCE_KEY);
AuditManager.setAuditEnable(true);
//设置 SQL 审计收集器
MessageCollector collector = new ConsoleMessageCollector();
AuditManager.setMessageCollector(collector);
accountMapper = bootstrap.getMapper(AccountMapper.class); accountMapper = bootstrap.getMapper(AccountMapper.class);
}
@After
public void destroy() {
this.dataSource.shutdown();
DataSourceKey.clear();
} }
@Test @Test
@SneakyThrows
public void testUpdateChain() { public void testUpdateChain() {
UpdateChain.of(Account.class) UpdateChain.of(Account.class)
.set(Account::getUserName, "张三") .set(Account::getUserName, "张三")
@ -71,7 +87,19 @@ public class UpdateChainTest {
.update(); .update();
Account account = accountMapper.selectOneById(1); Account account = accountMapper.selectOneById(1);
System.out.println(account); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String toParse = "2020-01-11";
assertThat(account).isNotNull()
.extracting(
Account::getUserName, Account::getAge,
Account::getSex, Account::getBirthday,
Account::getOptions, Account::getDelete,
Account::getArticles, Account::getTitle)
.containsExactly(
"张*", 19,
SexEnum.TYPE1, format.parse(toParse),
Collections.singletonMap("key", "value1"), false,
Collections.emptyList(), null);
} }
@Test @Test
@ -82,9 +110,10 @@ public class UpdateChainTest {
.and(Account::getAge).eq(18) .and(Account::getAge).eq(18)
.update(); .update();
QueryChain.of(accountMapper) List<Account> list = QueryChain.of(accountMapper).list();
.list() assertThat(list).hasSize(2)
.forEach(System.out::println); .extracting(Account::getId, Account::getUserName, Account::getAge)
.containsExactly(tuple(1L, "张*", 18), tuple(2L, "王麻**叔", 19));
} }
@Test @Test
@ -96,7 +125,11 @@ public class UpdateChainTest {
.where(ACCOUNT.ID.eq(4)) .where(ACCOUNT.ID.eq(4))
.toSQL(); .toSQL();
System.out.println(sql); String expectSQL = "UPDATE `tb_account` " +
"LEFT JOIN `tb_article` AS `ar` ON `tb_account`.`id` = `ar`.`account_id` " +
"SET `age` = 18 , `accountId` = 4 WHERE `id` = 4";
assertThat(sql).isEqualTo(expectSQL);
} }
} }

View File

@ -0,0 +1,11 @@
-- 设置主键自增时,初始化数据不显式设置 ID
INSERT INTO tb_account(`user_name`, `age`, `sex`, `birthday`, `options`, `is_delete`)
VALUES ('张三', 18, 0,'2020-01-11', '{"key":"value1"}',0),
('王麻子叔叔', 19, 1, '2021-03-21', '{"key":"value2"}',0);
INSERT INTO tb_article(`account_id`, `title`, `content`, `is_delete`)
VALUES (1, '标题1', '内容1',0),
(2, '标题2', '内容2',0),
(1, '标题3', '内容3',0);

View File

@ -0,0 +1,22 @@
CREATE TABLE IF NOT EXISTS `tb_account`
(
`id` INTEGER AUTO_INCREMENT,
`user_name` VARCHAR(100),
`age` Integer,
`sex` Integer,
`birthday` DATETIME,
`options` VARCHAR(1024),
`is_delete` Integer,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS `tb_article`
(
`id` INTEGER AUTO_INCREMENT,
`account_id` Integer,
`title` VARCHAR(100),
`content` text,
`is_delete` Integer,
PRIMARY KEY(id)
);

View File

@ -0,0 +1,5 @@
-- 使用主键生成器生成主键,初始化数据时仍然手动设置 ID
INSERT INTO tb_account7(`id`, `user_name`, `age`)
VALUES (1, '张三', 18),
(2, '王麻子叔叔', 19);

View File

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS `tb_account7`
(
`id` INTEGER,
`user_name` VARCHAR(100),
`age` Integer,
PRIMARY KEY(id)
);

View File

@ -0,0 +1,5 @@
-- 没有主键生成策略,手动插入 ID
INSERT INTO tb_account6(`id`, `user_name`, `age`)
VALUES (1, '张三', 18),
(2, '王麻子叔叔', 19);

View File

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS `tb_account6`
(
`id` INTEGER,
`user_name` VARCHAR(100),
`age` Integer,
PRIMARY KEY(id)
);

View File

@ -1,11 +1,11 @@
CREATE TABLE IF NOT EXISTS `tb_account` CREATE TABLE IF NOT EXISTS `tb_account`
( (
`id` INTEGER auto_increment, `id` INTEGER,
`user_name` VARCHAR(100), `user_name` VARCHAR(100),
`age` Integer `age` Integer,
PRIMARY KEY(id)
); );
CREATE TABLE IF NOT EXISTS `tb_idcard` CREATE TABLE IF NOT EXISTS `tb_idcard`
( (
`account_id` Integer, `account_id` Integer,
@ -13,39 +13,38 @@ CREATE TABLE IF NOT EXISTS `tb_idcard`
`content` text `content` text
); );
CREATE TABLE IF NOT EXISTS `tb_idcard_mapping` CREATE TABLE IF NOT EXISTS `tb_idcard_mapping`
( (
`account_id` Integer, `account_id` Integer,
`idcard_id` Integer `idcard_id` Integer
); );
CREATE TABLE IF NOT EXISTS `tb_book` CREATE TABLE IF NOT EXISTS `tb_book`
( (
`id` INTEGER auto_increment, `id` INTEGER,
`account_id` Integer, `account_id` Integer,
`title` VARCHAR(100), `title` VARCHAR(100),
`content` text `content` text,
PRIMARY KEY(id)
); );
CREATE TABLE IF NOT EXISTS `tb_role` CREATE TABLE IF NOT EXISTS `tb_role`
( (
`id` INTEGER auto_increment, `id` INTEGER,
`name` VARCHAR(100) `name` VARCHAR(100),
PRIMARY KEY(id)
); );
CREATE TABLE IF NOT EXISTS `tb_role_mapping` CREATE TABLE IF NOT EXISTS `tb_role_mapping`
( (
`account_id` INTEGER , `account_id` INTEGER ,
`role_id` INTEGER `role_id` INTEGER
); );
CREATE TABLE IF NOT EXISTS `tb_menu` CREATE TABLE IF NOT EXISTS `tb_menu`
( (
`id` INTEGER auto_increment, `id` INTEGER,
`parent_id` INTEGER, `parent_id` INTEGER,
`name` VARCHAR(100) `name` VARCHAR(100),
PRIMARY KEY(id)
); );

View File

@ -0,0 +1,85 @@
[
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
}
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"2": {
"id": 2,
"name": "角色2",
"accounts": [
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
},
"3": {
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
}
}
]

View File

@ -0,0 +1,112 @@
[
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
}
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"2": {
"id": 2,
"name": "角色2",
"accounts": [
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
},
"3": {
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
}
},
{
"id": 3,
"userName": "沙和尚",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 4,
"userName": "六耳猕猴",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 5,
"userName": "王麻子叔叔",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]

View File

@ -0,0 +1,155 @@
[
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [
{
"id": 1,
"name": "角色1",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
},
{
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
]
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [
{
"id": 1,
"name": "角色1",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
},
{
"id": 2,
"name": "角色2",
"accounts": [
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
},
{
"id": 3,
"name": "角色3",
"accounts": [
{
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
},
{
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": null
}
]
}
]
},
{
"id": 3,
"userName": "沙和尚",
"age": 19,
"idCard": null,
"books": [],
"roles": null
},
{
"id": 4,
"userName": "六耳猕猴",
"age": 19,
"idCard": null,
"books": [],
"roles": null
},
{
"id": 5,
"userName": "王麻子叔叔",
"age": 19,
"idCard": null,
"books": [],
"roles": null
}
]

View File

@ -0,0 +1,138 @@
[
{
"id": 1,
"accountId": 1,
"title": "图书1",
"content": "内容1",
"account": {
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
},
{
"id": 2,
"accountId": 2,
"title": "图书2",
"content": "内容2",
"account": {
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"2": {
"id": 2,
"name": "角色2",
"accounts": []
},
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
},
{
"id": 3,
"accountId": 1,
"title": "图书3",
"content": "内容2",
"account": {
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
},
{
"id": 4,
"accountId": 1,
"title": "图书4",
"content": "内容2",
"account": {
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
},
{
"id": 5,
"accountId": 1,
"title": "图书5",
"content": "内容2",
"account": {
"id": 1,
"userName": "孙悟空",
"age": 18,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
},
{
"id": 6,
"accountId": 2,
"title": "图书6",
"content": "内容2",
"account": {
"id": 2,
"userName": "猪八戒",
"age": 19,
"idCard": null,
"books": [],
"roles": [],
"rolesMap": {
"2": {
"id": 2,
"name": "角色2",
"accounts": []
},
"3": {
"id": 3,
"name": "角色3",
"accounts": []
}
}
}
}
]

View File

@ -0,0 +1,90 @@
[
{
"id": 1,
"parentId": 0,
"name": "顶级菜单1",
"parent": null,
"children": [
{
"id": 4,
"parentId": 1,
"name": "子菜单4",
"parent": null,
"children": [
{
"id": 9,
"parentId": 4,
"name": "子菜单9",
"parent": null,
"children": null
},
{
"id": 10,
"parentId": 4,
"name": "子菜单10",
"parent": null,
"children": null
}
]
},
{
"id": 5,
"parentId": 1,
"name": "子菜单5",
"parent": null,
"children": [
{
"id": 11,
"parentId": 5,
"name": "子菜单11",
"parent": null,
"children": null
},
{
"id": 12,
"parentId": 5,
"name": "子菜单12",
"parent": null,
"children": null
}
]
}
]
},
{
"id": 2,
"parentId": 0,
"name": "顶级菜单2",
"parent": null,
"children": []
},
{
"id": 3,
"parentId": 0,
"name": "顶级菜单3",
"parent": null,
"children": [
{
"id": 6,
"parentId": 3,
"name": "子菜单6",
"parent": null,
"children": []
},
{
"id": 7,
"parentId": 3,
"name": "子菜单7",
"parent": null,
"children": []
},
{
"id": 8,
"parentId": 3,
"name": "子菜单8",
"parent": null,
"children": []
}
]
}
]

View File

@ -0,0 +1,120 @@
[
{
"id": 1,
"parentId": 0,
"name": "顶级菜单1",
"parent": null,
"children": [
{
"id": 4,
"parentId": 1,
"name": "子菜单4",
"parent": {
"id": 1,
"parentId": 0,
"name": "顶级菜单1",
"parent": null,
"children": null
},
"children": [
{
"id": 9,
"parentId": 4,
"name": "子菜单9",
"parent": null,
"children": null
},
{
"id": 10,
"parentId": 4,
"name": "子菜单10",
"parent": null,
"children": null
}
]
},
{
"id": 5,
"parentId": 1,
"name": "子菜单5",
"parent": {
"id": 1,
"parentId": 0,
"name": "顶级菜单1",
"parent": null,
"children": null
},
"children": [
{
"id": 11,
"parentId": 5,
"name": "子菜单11",
"parent": null,
"children": null
},
{
"id": 12,
"parentId": 5,
"name": "子菜单12",
"parent": null,
"children": null
}
]
}
]
},
{
"id": 2,
"parentId": 0,
"name": "顶级菜单2",
"parent": null,
"children": []
},
{
"id": 3,
"parentId": 0,
"name": "顶级菜单3",
"parent": null,
"children": [
{
"id": 6,
"parentId": 3,
"name": "子菜单6",
"parent": {
"id": 3,
"parentId": 0,
"name": "顶级菜单3",
"parent": null,
"children": null
},
"children": []
},
{
"id": 7,
"parentId": 3,
"name": "子菜单7",
"parent": {
"id": 3,
"parentId": 0,
"name": "顶级菜单3",
"parent": null,
"children": null
},
"children": []
},
{
"id": 8,
"parentId": 3,
"name": "子菜单8",
"parent": {
"id": 3,
"parentId": 0,
"name": "顶级菜单3",
"parent": null,
"children": null
},
"children": []
}
]
}
]

View File

@ -4,7 +4,7 @@
<parent> <parent>
<artifactId>mybatis-flex-test</artifactId> <artifactId>mybatis-flex-test</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -6,15 +6,18 @@ mybatis-flex:
accountdb: accountdb:
url: jdbc:mysql://127.0.0.1:3306/db_account url: jdbc:mysql://127.0.0.1:3306/db_account
username: root username: root
password: 131496 password: 123456
break-after-acquire-failure: true
orderdb: orderdb:
url: jdbc:mysql://127.0.0.1:3306/db_order url: jdbc:mysql://127.0.0.1:3306/db_order
username: root username: root
password: 131496 password: 123456
break-after-acquire-failure: true
stockdb: stockdb:
url: jdbc:mysql://127.0.0.1:3306/db_stock url: jdbc:mysql://127.0.0.1:3306/db_stock
username: root username: root
password: 131496 password: 123456
break-after-acquire-failure: true
server: server:
port: 2010 port: 2010
seata: seata:

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>mybatis-flex-test</artifactId> <artifactId>mybatis-flex-test</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,108 +1,108 @@
package com.mybatisflex.test.model; //package com.mybatisflex.test.model;
//
import com.mybatisflex.annotation.*; //import com.mybatisflex.annotation.*;
//
import java.io.Serializable; //import java.io.Serializable;
import java.util.List; //import java.util.List;
//
/** ///**
* 字段绑定测试 // * 字段绑定测试
* @author Ice 2023/09/16 // * @author Ice 2023/09/16
* @version 1.0 // * @version 1.0
*/ // */
@Table("tb_user") //@Table("tb_user")
public class UserVO5 implements Serializable { //public class UserVO5 implements Serializable {
private static final long serialVersionUID = 474700189859144273L; // private static final long serialVersionUID = 474700189859144273L;
//
@Id // @Id
private Integer userId; // private Integer userId;
private String userName; // private String userName;
private String password; // private String password;
//
@RelationOneToOne( // @RelationOneToOne(
selfField = "userId", // selfField = "userId",
targetTable = "tb_id_card", // targetTable = "tb_id_card",
targetField = "id", // targetField = "id",
valueField = "idNumber" // valueField = "idNumber"
) // )
private String idNumberCustomFieldName; // private String idNumberCustomFieldName;
//
@RelationOneToMany( // @RelationOneToMany(
selfField = "userId", // selfField = "userId",
targetTable = "tb_user_order", // targetTable = "tb_user_order",
targetField = "userId", // targetField = "userId",
valueField = "orderId" // valueField = "orderId"
) // )
private List<Integer> orderIdList; // private List<Integer> orderIdList;
//
@RelationManyToMany( // @RelationManyToMany(
selfField = "userId", // selfField = "userId",
targetTable = "tb_role", // targetTable = "tb_role",
targetField = "roleId", // targetField = "roleId",
valueField = "roleName", // valueField = "roleName",
joinTable = "tb_user_role", // joinTable = "tb_user_role",
joinSelfColumn = "user_id", // joinSelfColumn = "user_id",
joinTargetColumn = "role_id" // joinTargetColumn = "role_id"
) // )
private List<String> roleNameList; // private List<String> roleNameList;
//
public Integer getUserId() { // public Integer getUserId() {
return userId; // return userId;
} // }
//
public void setUserId(Integer userId) { // public void setUserId(Integer userId) {
this.userId = userId; // this.userId = userId;
} // }
//
public String getUserName() { // public String getUserName() {
return userName; // return userName;
} // }
//
public void setUserName(String userName) { // public void setUserName(String userName) {
this.userName = userName; // this.userName = userName;
} // }
//
public String getPassword() { // public String getPassword() {
return password; // return password;
} // }
//
public void setPassword(String password) { // public void setPassword(String password) {
this.password = password; // this.password = password;
} // }
//
public String getIdNumberCustomFieldName() { // public String getIdNumberCustomFieldName() {
return idNumberCustomFieldName; // return idNumberCustomFieldName;
} // }
//
public void setIdNumberCustomFieldName(String idNumberCustomFieldName) { // public void setIdNumberCustomFieldName(String idNumberCustomFieldName) {
this.idNumberCustomFieldName = idNumberCustomFieldName; // this.idNumberCustomFieldName = idNumberCustomFieldName;
} // }
//
public List<Integer> getOrderIdList() { // public List<Integer> getOrderIdList() {
return orderIdList; // return orderIdList;
} // }
//
public void setOrderIdList(List<Integer> orderIdList) { // public void setOrderIdList(List<Integer> orderIdList) {
this.orderIdList = orderIdList; // this.orderIdList = orderIdList;
} // }
//
public List<String> getRoleNameList() { // public List<String> getRoleNameList() {
return roleNameList; // return roleNameList;
} // }
//
public void setRoleNameList(List<String> roleNameList) { // public void setRoleNameList(List<String> roleNameList) {
this.roleNameList = roleNameList; // this.roleNameList = roleNameList;
} // }
//
@Override // @Override
public String toString() { // public String toString() {
return "UserVO5{" + // return "UserVO5{" +
"userId=" + userId + // "userId=" + userId +
", userName='" + userName + '\'' + // ", userName='" + userName + '\'' +
", password='" + password + '\'' + // ", password='" + password + '\'' +
", idNumberCustomFieldName='" + idNumberCustomFieldName + '\'' + // ", idNumberCustomFieldName='" + idNumberCustomFieldName + '\'' +
", orderIdList=" + orderIdList + // ", orderIdList=" + orderIdList +
", roleNameList=" + roleNameList + // ", roleNameList=" + roleNameList +
'}'; // '}';
} // }
} //}

View File

@ -7,7 +7,7 @@ spring:
# driver-class-name: com.mysql.cj.jdbc.Driver # driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/flex_test url: jdbc:mysql://localhost:3306/flex_test
username: root username: root
password: 12345678 password: 123456
# driver-class-name: # driver-class-name:
# datasource: # datasource:
# driver-class-name: org.h2.Driver # driver-class-name: org.h2.Driver

View File

@ -8,7 +8,7 @@ DROP TABLE IF EXISTS `tb_account`;
CREATE TABLE `tb_account` CREATE TABLE `tb_account`
( (
`id` int NOT NULL AUTO_INCREMENT, `id` int NOT NULL AUTO_INCREMENT,
`user_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `user_name` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL, `age` int NULL DEFAULT NULL,
`birthday` datetime NULL DEFAULT NULL, `birthday` datetime NULL DEFAULT NULL,
`gender` int NULL DEFAULT NULL, `gender` int NULL DEFAULT NULL,
@ -17,7 +17,6 @@ CREATE TABLE `tb_account`
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 5 AUTO_INCREMENT = 5
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -38,14 +37,13 @@ CREATE TABLE `tb_article`
( (
`id` int NOT NULL AUTO_INCREMENT, `id` int NOT NULL AUTO_INCREMENT,
`account_id` int NULL DEFAULT NULL, `account_id` int NULL DEFAULT NULL,
`title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `title` varchar(100) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL, `content` text CHARACTER SET utf8mb4 NULL,
`is_delete` int NULL DEFAULT NULL, `is_delete` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 3 AUTO_INCREMENT = 3
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
@ -65,13 +63,12 @@ DROP TABLE IF EXISTS `tb_good`;
CREATE TABLE `tb_good` CREATE TABLE `tb_good`
( (
`good_id` int NOT NULL AUTO_INCREMENT, `good_id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `name` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`price` decimal(10, 2) NULL DEFAULT NULL, `price` decimal(10, 2) NULL DEFAULT NULL,
PRIMARY KEY (`good_id`) USING BTREE PRIMARY KEY (`good_id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 10 AUTO_INCREMENT = 10
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -105,11 +102,10 @@ DROP TABLE IF EXISTS `tb_id_card`;
CREATE TABLE `tb_id_card` CREATE TABLE `tb_id_card`
( (
`id` int NOT NULL AUTO_INCREMENT, `id` int NOT NULL AUTO_INCREMENT,
`id_number` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `id_number` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
@ -131,12 +127,11 @@ DROP TABLE IF EXISTS `tb_inner`;
CREATE TABLE `tb_inner` CREATE TABLE `tb_inner`
( (
`id` int NOT NULL AUTO_INCREMENT, `id` int NOT NULL AUTO_INCREMENT,
`type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `type` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 2 AUTO_INCREMENT = 2
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
@ -157,7 +152,6 @@ CREATE TABLE `tb_order`
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 6 AUTO_INCREMENT = 6
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -186,7 +180,6 @@ CREATE TABLE `tb_order_good`
`good_id` int NOT NULL `good_id` int NOT NULL
) ENGINE = InnoDB ) ENGINE = InnoDB
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -226,12 +219,11 @@ DROP TABLE IF EXISTS `tb_outer`;
CREATE TABLE `tb_outer` CREATE TABLE `tb_outer`
( (
`id` int NOT NULL AUTO_INCREMENT, `id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `name` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
@ -247,13 +239,12 @@ DROP TABLE IF EXISTS `tb_role`;
CREATE TABLE `tb_role` CREATE TABLE `tb_role`
( (
`role_id` int NOT NULL AUTO_INCREMENT, `role_id` int NOT NULL AUTO_INCREMENT,
`role_key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `role_key` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`role_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `role_name` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
PRIMARY KEY (`role_id`) USING BTREE PRIMARY KEY (`role_id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 5 AUTO_INCREMENT = 5
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -275,13 +266,12 @@ DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` CREATE TABLE `tb_user`
( (
`user_id` int NOT NULL AUTO_INCREMENT, `user_id` int NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `user_name` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL,
PRIMARY KEY (`user_id`) USING BTREE PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB ) ENGINE = InnoDB
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -306,7 +296,6 @@ CREATE TABLE `tb_user_order`
`order_id` int NOT NULL `order_id` int NOT NULL
) ENGINE = InnoDB ) ENGINE = InnoDB
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
@ -335,7 +324,6 @@ CREATE TABLE `tb_user_role`
`role_id` int NOT NULL `role_id` int NOT NULL
) ENGINE = InnoDB ) ENGINE = InnoDB
CHARACTER SET = utf8mb4 CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------

View File

@ -6,10 +6,10 @@ SET FOREIGN_KEY_CHECKS = 0;
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `tb_disease`; DROP TABLE IF EXISTS `tb_disease`;
CREATE TABLE `tb_disease` ( CREATE TABLE `tb_disease` (
`disease_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'ID', `disease_id` varchar(32) CHARACTER SET utf8mb4 NOT NULL COMMENT 'ID',
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '疾病名称', `name` varchar(32) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '疾病名称',
PRIMARY KEY (`disease_id`) USING BTREE PRIMARY KEY (`disease_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '疾病信息' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '疾病信息' ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
-- Records of tb_disease -- Records of tb_disease
@ -24,12 +24,12 @@ INSERT INTO `tb_disease` VALUES ('4', '免疫系统疾病');
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `tb_patient`; DROP TABLE IF EXISTS `tb_patient`;
CREATE TABLE `tb_patient` ( CREATE TABLE `tb_patient` (
`patient_id` int NOT NULL AUTO_INCREMENT COMMENT 'ID', `patient_id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '姓名', `name` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '姓名',
`disease_ids` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '所患病症(对应字符串类型) 英文逗号 分割', `disease_ids` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '所患病症(对应字符串类型) 英文逗号 分割',
`tag_ids` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '患者标签(对应数字类型) / 分割', `tag_ids` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '患者标签(对应数字类型) / 分割',
PRIMARY KEY (`patient_id`) USING BTREE PRIMARY KEY (`patient_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '患者信息' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '患者信息' ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
-- Records of tb_patient -- Records of tb_patient
@ -44,10 +44,10 @@ INSERT INTO `tb_patient` VALUES (4, '赵六', '1,2,3,4', '1/2/3');
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `tb_tag`; DROP TABLE IF EXISTS `tb_tag`;
CREATE TABLE `tb_tag` ( CREATE TABLE `tb_tag` (
`tag_id` int NOT NULL AUTO_INCREMENT COMMENT 'ID', `tag_id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '标签名', `name` varchar(32) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '标签名',
PRIMARY KEY (`tag_id`) USING BTREE PRIMARY KEY (`tag_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '标签' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '标签' ROW_FORMAT = Dynamic;
-- ---------------------------- -- ----------------------------
-- Records of tb_tag -- Records of tb_tag

View File

@ -68,16 +68,16 @@ class CloneTest {
QueryWrapper queryWrapper = newQueryWrapper(); QueryWrapper queryWrapper = newQueryWrapper();
QueryWrapper queryWrapper1 = queryWrapper.clone(); QueryWrapper queryWrapper1 = queryWrapper.clone();
QueryWrapper queryWrapper2 = SerialUtil.cloneObject(queryWrapper); QueryWrapper queryWrapper2 = SerialUtil.cloneObject(queryWrapper);
QueryWrapper queryWrapper3 = SerialUtil.cloneObject(queryWrapper, QueryWrapper.class); // QueryWrapper queryWrapper3 = SerialUtil.cloneObject(queryWrapper, QueryWrapper.class);
System.err.println(SerialUtil.toJSONString(queryWrapper)); System.err.println(SerialUtil.toJSONString(queryWrapper));
System.out.println(queryWrapper.toSQL()); System.out.println(queryWrapper.toSQL());
System.out.println(queryWrapper1.toSQL()); System.out.println(queryWrapper1.toSQL());
System.out.println(queryWrapper2.toSQL()); System.out.println(queryWrapper2.toSQL());
System.out.println(queryWrapper3.toSQL()); // System.out.println(queryWrapper3.toSQL());
Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper1.toSQL()); Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper1.toSQL());
Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper2.toSQL()); Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper2.toSQL());
Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper3.toSQL()); // Assertions.assertEquals(queryWrapper.toSQL(), queryWrapper3.toSQL());
} }
private void calcTime(int count, String type, Supplier<QueryWrapper> supplier) { private void calcTime(int count, String type, Supplier<QueryWrapper> supplier) {

View File

@ -16,12 +16,14 @@
package com.mybatisflex.test.mapper; package com.mybatisflex.test.mapper;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db; import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row; import com.mybatisflex.core.row.Row;
import com.mybatisflex.test.model.Account; import com.mybatisflex.test.model.Account;
import com.mybatisflex.test.model.AccountVO; import com.mybatisflex.test.model.AccountVO;
import com.mybatisflex.test.model.AccountVO2; import com.mybatisflex.test.model.AccountVO2;
import lombok.val;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -56,7 +58,7 @@ class AccountMapperTest {
long count = accountMapper.selectCountByQuery(queryWrapper); long count = accountMapper.selectCountByQuery(queryWrapper);
Assertions.assertEquals(2, count); // Assertions.assertEquals(2, count);
queryWrapper = QueryWrapper.create() queryWrapper = QueryWrapper.create()
.select(distinct(ACCOUNT.AGE)) .select(distinct(ACCOUNT.AGE))
@ -120,16 +122,15 @@ class AccountMapperTest {
void testEnum() { void testEnum() {
Account account = new Account(); Account account = new Account();
account.setId(1L); account.setId(1L);
// account.setGender(Gender.MALE); account.setAge(18);
accountMapper.update(account); int result = accountMapper.update(account);
System.out.println(result);
} }
@Test @Test
void testSelectList() { void testSelectListWithNullQuery() {
List<Account> accounts = accountMapper.selectListByQuery(null); Assertions.assertThrows(Exception.class, () -> accountMapper.selectListByQuery(null));
System.out.println(accounts); Assertions.assertThrows(Exception.class, () -> Db.selectListByQuery("tb_account", null));
List<Row> account = Db.selectListByQuery("tb_account", null);
System.out.println(account);
} }
@Test @Test
@ -137,13 +138,13 @@ class AccountMapperTest {
Account account = new Account(); Account account = new Account();
account.setAge(10); account.setAge(10);
Assertions.assertThrows(Exception.class, () -> Assertions.assertThrows(Exception.class, () ->
accountMapper.updateByQuery(account, QueryWrapper.create())); LogicDeleteManager.execWithoutLogicDelete(()->accountMapper.updateByQuery(account, QueryWrapper.create())));
} }
@Test @Test
void testDeleteAll() { void testDeleteAll() {
Assertions.assertThrows(Exception.class, () -> Assertions.assertThrows(Exception.class, () ->
accountMapper.deleteByQuery(QueryWrapper.create())); LogicDeleteManager.execWithoutLogicDelete(()-> accountMapper.deleteByQuery(QueryWrapper.create())));
} }
@Test @Test

View File

@ -83,7 +83,7 @@ class ActiveRecordTest {
.setGoodId(1) .setGoodId(1)
.removeById(); .removeById();
Assertions.assertTrue(removed); System.out.println(removed);
} }
@Test @Test
@ -109,8 +109,9 @@ class ActiveRecordTest {
.where(Good::getName).eq("摆渡人") .where(Good::getName).eq("摆渡人")
.one(); .one();
Assertions.assertEquals(good1, good2); System.out.println(good1);
Assertions.assertEquals(good1, good3); System.out.println(good2);
System.out.println(good3);
} }
@Test @Test
@ -127,7 +128,7 @@ class ActiveRecordTest {
.leftJoin(USER_ROLE).as("ur").on(USER_ROLE.USER_ID.eq(USER.USER_ID)) .leftJoin(USER_ROLE).as("ur").on(USER_ROLE.USER_ID.eq(USER.USER_ID))
.leftJoin(ROLE).as("r").on(USER_ROLE.ROLE_ID.eq(ROLE.ROLE_ID)) .leftJoin(ROLE).as("r").on(USER_ROLE.ROLE_ID.eq(ROLE.ROLE_ID))
.where(USER.USER_ID.eq(2)) .where(USER.USER_ID.eq(2))
.one(); .list().get(0);
User user2 = User.create() User user2 = User.create()
.where(USER.USER_ID.eq(2)) .where(USER.USER_ID.eq(2))

View File

@ -40,7 +40,7 @@ class MyAccountMapperTest {
@Test @Test
void insertBatch() { void insertBatch() {
List<Account> accounts = new ArrayList<>(); List<Account> accounts = new ArrayList<>();
for (int i = 0; i < 3_3334; i++) { for (int i = 0; i < 10; i++) {
Account account = new Account(); Account account = new Account();
account.setBirthday(new Date()); account.setBirthday(new Date());
account.setAge(i % 60); account.setAge(i % 60);
@ -56,7 +56,7 @@ class MyAccountMapperTest {
System.out.println("异常"); System.out.println("异常");
} }
int i = mapper.insertBatch(accounts, 1000); int i = mapper.insertBatch(accounts, 1000);
assertEquals(33334, i); assertEquals(10, i);
} }
} }

View File

@ -19,6 +19,7 @@ package com.mybatisflex.test.mapper;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.test.entity.Inner; import com.mybatisflex.test.entity.Inner;
import com.mybatisflex.test.entity.Outer; import com.mybatisflex.test.entity.Outer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -43,12 +44,8 @@ class OuterMapperTest {
void testInsert() { void testInsert() {
Outer outer = new Outer(); Outer outer = new Outer();
outer.setName("outer 01"); outer.setName("outer 01");
outerMapper.insertSelective(outer); int result = outerMapper.insertSelective(outer);
Assertions.assertEquals(result,1);
Inner inner = new Inner();
inner.setId(2);
inner.setType("inner type");
innerMapper.insertWithPk(inner);
} }
@Test @Test

View File

@ -280,10 +280,10 @@ class UserMapperTest {
System.err.println(user); System.err.println(user);
} }
@Test // @Test
public void testFieldBindRelations() { // public void testFieldBindRelations() {
List<UserVO5> userVO5List = userMapper.selectListWithRelationsByQueryAs(QueryWrapper.create(), UserVO5.class); // List<UserVO5> userVO5List = userMapper.selectListWithRelationsByQueryAs(QueryWrapper.create(), UserVO5.class);
System.out.println(userVO5List); // System.out.println(userVO5List);
} // }
} }

View File

@ -4,7 +4,7 @@
<parent> <parent>
<artifactId>mybatis-flex-test</artifactId> <artifactId>mybatis-flex-test</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,29 +1,29 @@
/* ///*
* Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). // * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
* <p> // * <p>
* Licensed under the Apache License, Version 2.0 (the "License"); // * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. // * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at // * You may obtain a copy of the License at
* <p> // * <p>
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* <p> // * <p>
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
*/ // */
//
package com.mybatisflex.test; //package com.mybatisflex.test;
//
import org.junit.jupiter.api.Test; //import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.boot.test.context.SpringBootTest;
//
@SpringBootTest //@SpringBootTest
class MybatisFlexSpringCloudTestApplicationTests { //class MybatisFlexSpringCloudTestApplicationTests {
//
@Test // @Test
void contextLoads() { // void contextLoads() {
} // }
//
} //}

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>mybatis-flex-test</artifactId> <artifactId>mybatis-flex-test</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<version>1.7.5</version> <version>1.7.6</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -15,7 +15,7 @@
<modules> <modules>
<module>mybatis-flex-native-test</module> <module>mybatis-flex-native-test</module>
<module>mybatis-flex-seata-test</module> <!-- <module>mybatis-flex-seata-test</module>-->
<module>mybatis-flex-spring-test</module> <module>mybatis-flex-spring-test</module>
<module>mybatis-flex-spring-boot-test</module> <module>mybatis-flex-spring-boot-test</module>
<module>mybatis-flex-spring-cloud-test</module> <module>mybatis-flex-spring-cloud-test</module>
@ -24,8 +24,32 @@
<properties> <properties>
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>8</maven.compiler.target>
<commons-io.version>2.15.1</commons-io.version>
<org.projectlombok.version>1.18.30</org.projectlombok.version>
<!-- 高版本基于 JDK17勿动 -->
<json-unit-assertj.version>2.38.0</json-unit-assertj.version>
</properties> </properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit-assertj</artifactId>
<version>${json-unit-assertj.version}</version>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -36,6 +60,11 @@
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
<annotationProcessorPaths> <annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</path>
<path> <path>
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId> <artifactId>mybatis-flex-processor</artifactId>

View File

@ -7,7 +7,7 @@
<groupId>com.mybatis-flex</groupId> <groupId>com.mybatis-flex</groupId>
<artifactId>parent</artifactId> <artifactId>parent</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<version>1.7.5</version> <version>1.7.6</version>
<name>mybatis-flex</name> <name>mybatis-flex</name>
<url>https://mybatis-flex.com</url> <url>https://mybatis-flex.com</url>
@ -55,7 +55,7 @@
<maven.compiler.source>8</maven.compiler.source> <maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target> <maven.compiler.target>8</maven.compiler.target>
<mybatis-flex.version>1.7.5</mybatis-flex.version> <mybatis-flex.version>1.7.6</mybatis-flex.version>
<mybatis.version>3.5.14</mybatis.version> <mybatis.version>3.5.14</mybatis.version>
<mybatis-spring.version>2.1.2</mybatis-spring.version> <mybatis-spring.version>2.1.2</mybatis-spring.version>

View File

@ -1,4 +1,4 @@
<h4 align="right"><strong>English</strong> | <a href="https://github.com/mybatis-flex/mybatis-flex/blob/main/readme_zh.md">简体中文</a></h4> <h4 align="right"><strong>English</strong> | <a href="./readme_zh.md">简体中文</a></h4>
<p align="center"> <p align="center">
<img src="./docs/assets/images/logo_en.png"/> <img src="./docs/assets/images/logo_en.png"/>

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