feat: Extensions for Kotlin

This commit is contained in:
kamosama 2023-08-07 21:59:09 +08:00
parent ebf6a073b8
commit 7fa117e0ac
14 changed files with 1122 additions and 0 deletions

112
mybatis-flex-kotlin/pom.xml Executable file
View File

@ -0,0 +1,112 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mybatis-flex</groupId>
<artifactId>parent</artifactId>
<version>1.4.8</version>
</parent>
<artifactId>mybatis-flex-kotlin</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin.version>1.9.0</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId>
<version>1.4.8</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>
<arg>-Xjvm-default=all</arg>
</args>
</configuration>
<executions>
<execution>
<id>kapt</id>
<goals>
<goal>kapt</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
<sourceDir>src/main/java</sourceDir>
</sourceDirs>
<annotationProcessorPaths>
<!-- 在此处指定你的注解处理器。 -->
<annotationProcessorPath>
<groupId>com.google.dagger</groupId>
<artifactId>dagger-compiler</artifactId>
<version>2.9</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</execution>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,37 @@
package com.mybatisflex.kotlin.db
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* 数据库配置对象暂时未启用
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
object DbConfig {
var url: String by IfNullVar { "" }
var username: String by IfNullVar { "" }
var password: String by IfNullVar { "" }
}
class IfNullVar<T : Any>(private var init: (() -> T)?) : ReadWriteProperty<Any?, T> {
private var _value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (_value == null) {
synchronized(this) {
if (_value == null) {
_value = init!!()
init = null
}
}
}
return this._value!!
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
_value = value
}
}

View File

@ -0,0 +1,49 @@
package com.mybatisflex.kotlin.entry
import com.mybatisflex.core.dialect.DialectFactory
import com.mybatisflex.core.table.TableInfoFactory
import com.mybatisflex.core.util.ArrayUtil
import com.mybatisflex.kotlin.extend.db.DB
import java.io.Serializable
/**
* 实体类父类继承该类后将赋予实体简单增删改操作
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
open class Entry :Serializable{
fun save(ignoreNulls: Boolean = true): Boolean {
val tableInfo = TableInfoFactory.ofEntityClass(this.javaClass)
//设置乐观锁版本字段的初始化数据
tableInfo.initVersionValueIfNecessary(this)
//设置租户ID
tableInfo.initTenantIdIfNecessary(this)
//设置逻辑删除字段的出初始化数据
tableInfo.initLogicDeleteValueIfNecessary(this)
//执行 onInsert 监听器
tableInfo.invokeOnInsertListener(this)
val values = tableInfo.buildInsertSqlArgs(this, ignoreNulls)
val sql = DialectFactory.getDialect().forInsertEntity(tableInfo, this, ignoreNulls)
return DB.insertBySql(sql, *values) == 1
}
fun update(ignoreNulls: Boolean = true): Boolean {
val tableInfo = TableInfoFactory.ofEntityClass(this.javaClass)
//执行 onUpdate 监听器
tableInfo.invokeOnUpdateListener(this)
val updateValues = tableInfo.buildUpdateSqlArgs(this, ignoreNulls, false)
val primaryValues = tableInfo.buildPkSqlArgs(this)
val tenantIdArgs = tableInfo.buildTenantIdArgs()
val sql = DialectFactory.getDialect().forUpdateEntity(tableInfo, this, ignoreNulls)
return DB.updateBySql(sql, *ArrayUtil.concat(updateValues, primaryValues, tenantIdArgs)) == 1
}
fun deleteById(): Boolean {
val tableInfo = TableInfoFactory.ofEntityClass(this.javaClass)
val primaryValues = tableInfo.buildPkSqlArgs(this)
val allValues = ArrayUtil.concat(primaryValues, tableInfo.buildTenantIdArgs())
val sql = DialectFactory.getDialect().forDeleteEntityById(tableInfo)
return DB.deleteBySql(sql, *allValues) == 1
}
}

View File

@ -0,0 +1,588 @@
package com.mybatisflex.kotlin.extend.db
import com.mybatisflex.core.BaseMapper
import com.mybatisflex.core.MybatisFlexBootstrap
import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.core.row.*
import com.mybatisflex.core.table.TableDef
import com.mybatisflex.core.table.TableInfoFactory
import com.mybatisflex.core.transaction.Propagation
import com.mybatisflex.kotlin.extend.entry.filter
import com.mybatisflex.kotlin.extend.entry.toEntities
import com.mybatisflex.kotlin.scope.QueryScope
import com.mybatisflex.kotlin.scope.queryScope
import java.util.function.BiConsumer
import java.util.function.Supplier
/**
* 数据库操作对象
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
object DB {
fun invoker(): RowMapperInvoker = Db.invoker()
fun invoker(environmentId: String): RowMapperInvoker = Db.invoker(environmentId)
inline fun <reified M : BaseMapper<*>> mapper(): M = MybatisFlexBootstrap.getInstance().getMapper(M::class.java)
inline fun <reified T : Any> queryOne(
vararg columns: QueryColumn,
schema: String? = null,
tableName: String? = null,
noinline init: QueryScope.() -> Unit
): T = queryRow(schema = schema, tableName = tableName, columns = columns, init = init).toEntity(T::class.java)
fun queryRow(
vararg columns: QueryColumn?,
schema: String? = null,
tableName: String? = null,
init: QueryScope.() -> Unit
): Row =
selectOneByQuery(
schema = schema,
tableName = tableName,
queryWrapper = queryScope(columns = columns, init = init)
)
inline fun <reified T> query(
vararg columns: QueryColumn?,
schema: String? = null,
tableName: String? = null,
noinline init: QueryScope.() -> Unit
): List<T> =
queryRows(schema = schema, tableName = tableName, columns = columns, init = init)
.toEntities()
fun queryRows(
vararg columns: QueryColumn?,
schema: String? = null,
tableName: String? = null,
init: QueryScope.() -> Unit
): List<Row> = selectListByQuery(
schema = schema, tableName = tableName,
queryWrapper = queryScope(columns = columns, init = init)
)
// filter-----------
inline fun <reified E> filter(
tableName: String,
schema: String,
vararg columns: QueryColumn?,
queryCondition: QueryCondition = QueryCondition.createEmpty()
): List<E> = selectListByQuery(
schema,
tableName,
queryScope(*columns).where(queryCondition)
).toEntities()
inline fun <reified E> filter(
vararg columns: QueryColumn?,
init: () -> QueryCondition
): List<E> {
val tableInfo = TableInfoFactory.ofEntityClass(E::class.java)
return filter<E>(
columns = columns,
schema = tableInfo.schema,
tableName = tableInfo.tableName,
queryCondition = init()
)
}
inline fun <reified E, T : TableDef> filter(
tableDef: T,
vararg columns: QueryColumn?,
init: T.() -> QueryCondition
): List<E> = tableDef.filter(columns = columns, init = init)
// ----------------------
fun insert(schema: String?, tableName: String?, row: Row?): Int {
return Db.insert(schema, tableName, row)
}
fun insert(tableName: String?, row: Row?): Int {
return Db.insert(null as String?, tableName, row)
}
fun insertBySql(sql: String?, vararg args: Any?): Int {
return Db.insertBySql(sql, *args)
}
fun insertBatch(schema: String?, tableName: String?, rows: Collection<Row?>): IntArray {
return insertBatch(schema, tableName, rows, rows.size)
}
fun insertBatch(tableName: String?, rows: Collection<Row?>): IntArray {
return insertBatch(null as String?, tableName, rows, rows.size)
}
fun insertBatch(schema: String?, tableName: String?, rows: Collection<Row?>, batchSize: Int): IntArray {
return Db.insertBatch(schema, tableName, rows, batchSize)
}
fun insertBatch(tableName: String?, rows: Collection<Row>, batchSize: Int): IntArray {
return Db.insertBatch(tableName, rows)
}
fun insertBatchWithFirstRowColumns(schema: String?, tableName: String?, rows: List<Row?>?): Int {
return Db.insertBatchWithFirstRowColumns(schema, tableName, rows)
}
fun insertBatchWithFirstRowColumns(tableName: String?, rows: List<Row?>?): Int {
return Db.insertBatchWithFirstRowColumns(null as String?, tableName, rows)
}
fun deleteBySql(sql: String?, vararg args: Any?): Int {
return Db.deleteBySql(sql, *args)
}
fun deleteById(schema: String?, tableName: String?, row: Row?): Int {
return Db.deleteById(schema, tableName, row)
}
fun deleteById(tableName: String?, row: Row?): Int {
return Db.deleteById(null as String?, tableName, row)
}
fun deleteById(schema: String?, tableName: String?, primaryKey: String?, id: Any?): Int {
return Db.deleteById(schema, tableName, primaryKey, id)
}
fun deleteById(tableName: String?, primaryKey: String?, id: Any?): Int {
return Db.deleteById(null as String?, tableName, primaryKey, id)
}
fun deleteBatchByIds(schema: String?, tableName: String?, primaryKey: String?, ids: Collection<*>?): Int {
return Db.deleteBatchByIds(schema, tableName, primaryKey, ids)
}
fun deleteBatchByIds(tableName: String?, primaryKey: String?, ids: Collection<*>?): Int {
return Db.deleteBatchByIds(null as String?, tableName, primaryKey, ids)
}
fun deleteByMap(schema: String?, tableName: String?, whereColumns: Map<String?, Any?>?): Int {
return Db.deleteByQuery(
schema, tableName, QueryWrapper()
.where(whereColumns)
)
}
fun deleteByMap(tableName: String?, whereColumns: Map<String?, Any?>?): Int {
return Db.deleteByQuery(
null as String?, tableName, QueryWrapper()
.where(whereColumns)
)
}
fun deleteByCondition(schema: String?, tableName: String?, condition: QueryCondition?): Int {
return Db.deleteByQuery(
schema, tableName, QueryWrapper()
.where(condition)
)
}
fun deleteByCondition(tableName: String?, condition: QueryCondition?): Int {
return Db.deleteByQuery(
null as String?, tableName, QueryWrapper()
.where(condition)
)
}
fun deleteByQuery(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): Int {
return Db.deleteByQuery(schema, tableName, queryWrapper)
}
fun deleteByQuery(tableName: String?, queryWrapper: QueryWrapper?): Int {
return Db.deleteByQuery(null as String?, tableName, queryWrapper)
}
fun updateBySql(sql: String?, vararg args: Any?): Int {
return Db.updateBySql(sql, *args)
}
fun updateBatch(sql: String?, batchArgsSetter: BatchArgsSetter): IntArray {
return Db.updateBatch(sql, batchArgsSetter)
}
fun updateById(schema: String?, tableName: String?, row: Row?): Int {
return Db.updateById(schema, tableName, row)
}
fun updateById(tableName: String?, row: Row?): Int {
return Db.updateById(null as String?, tableName, row)
}
fun updateByMap(schema: String?, tableName: String?, data: Row?, whereColumns: Map<String?, Any?>?): Int {
return Db.updateByQuery(
schema, tableName, data, QueryWrapper()
.where(whereColumns)
)
}
fun updateByMap(tableName: String?, data: Row?, whereColumns: Map<String?, Any?>?): Int {
return Db.updateByQuery(
null as String?, tableName, data, QueryWrapper()
.where(whereColumns)
)
}
fun updateByCondition(schema: String?, tableName: String?, data: Row?, condition: QueryCondition?): Int {
return Db.updateByQuery(
schema, tableName, data, QueryWrapper()
.where(condition)
)
}
fun updateByCondition(tableName: String?, data: Row?, condition: QueryCondition?): Int {
return Db.updateByQuery(
null as String?, tableName, data, QueryWrapper()
.where(condition)
)
}
fun updateByQuery(schema: String?, tableName: String?, data: Row?, queryWrapper: QueryWrapper?): Int {
return Db.updateByQuery(schema, tableName, data, queryWrapper)
}
fun updateByQuery(tableName: String?, data: Row?, queryWrapper: QueryWrapper?): Int {
return Db.updateByQuery(null as String?, tableName, data, queryWrapper)
}
fun updateBatchById(schema: String?, tableName: String?, rows: List<Row?>?): Int {
return Db.updateBatchById(schema, tableName, rows)
}
fun updateBatchById(tableName: String?, rows: List<Row?>?): Int {
return Db.updateBatchById(null as String?, tableName, rows)
}
fun <T> updateEntitiesBatch(entities: Collection<T>?, batchSize: Int): Int {
return Db.updateEntitiesBatch(entities, batchSize)
}
fun <T> updateEntitiesBatch(entities: Collection<T>?): Int {
return updateEntitiesBatch(entities, 1000)
}
fun updateNumberAddByQuery(
schema: String?,
tableName: String?,
fieldName: String?,
value: Number?,
queryWrapper: QueryWrapper?
): Int {
return Db.updateNumberAddByQuery(schema, tableName, fieldName, value, queryWrapper)
}
fun updateNumberAddByQuery(
tableName: String?,
fieldName: String?,
value: Number?,
queryWrapper: QueryWrapper?
): Int {
return Db.updateNumberAddByQuery(null as String?, tableName, fieldName, value, queryWrapper)
}
fun <M> executeBatch(
totalSize: Int,
batchSize: Int,
mapperClass: Class<M>?,
consumer: BiConsumer<M, Int?>?
): IntArray {
return Db.executeBatch(totalSize, batchSize, mapperClass, consumer)
}
fun selectOneBySql(sql: String?, vararg args: Any?): Row {
return Db.selectOneBySql(sql, *args)
}
fun selectOneById(schema: String?, tableName: String?, row: Row?): Row {
return Db.selectOneById(schema, tableName, row)
}
fun selectOneById(tableName: String?, row: Row?): Row {
return Db.selectOneById(null as String?, tableName, row)
}
fun selectOneById(schema: String?, tableName: String?, primaryKey: String?, id: Any?): Row {
return Db.selectOneById(schema, tableName, primaryKey, id)
}
fun selectOneById(tableName: String?, primaryKey: String?, id: Any?): Row {
return Db.selectOneById(null as String?, tableName, primaryKey, id)
}
fun selectOneByMap(schema: String?, tableName: String?, whereColumns: Map<String, Any>?): Row {
return Db.selectOneByQuery(
schema, tableName, QueryWrapper()
.where(whereColumns).limit(1)
)
}
fun selectOneByMap(tableName: String?, whereColumns: Map<String, Any>?): Row {
return Db.selectOneByQuery(
null as String?, tableName, QueryWrapper().where(whereColumns).limit(1)
)
}
fun selectOneByCondition(schema: String?, tableName: String?, condition: QueryCondition?): Row {
return Db.selectOneByQuery(
schema, tableName, QueryWrapper()
.where(condition).limit(1)
)
}
fun selectOneByCondition(tableName: String?, condition: QueryCondition?): Row {
return Db.selectOneByQuery(
null as String?, tableName, QueryWrapper()
.where(condition).limit(1)
)
}
fun selectOneByQuery(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): Row {
return Db.selectOneByQuery(schema, tableName, queryWrapper)
}
fun selectOneByQuery(tableName: String?, queryWrapper: QueryWrapper?): Row {
return Db.selectOneByQuery(null as String?, tableName, queryWrapper)
}
fun selectOneByQuery(queryWrapper: QueryWrapper?): Row {
return Db.selectOneByQuery(queryWrapper)
}
fun selectListBySql(sql: String?, vararg args: Any?): List<Row> {
return Db.selectListBySql(sql, *args)
}
fun selectListByMap(schema: String?, tableName: String?, whereColumns: Map<String?, Any?>?): List<Row> {
return Db.selectListByQuery(
schema, tableName, QueryWrapper()
.where(whereColumns)
)
}
fun selectListByMap(tableName: String?, whereColumns: Map<String?, Any?>?): List<Row> {
return Db.selectListByMap(tableName, whereColumns)
}
fun selectListByMap(schema: String?, tableName: String?, whereColumns: Map<String?, Any?>?, count: Int): List<Row> {
return Db.selectListByMap(schema, tableName, whereColumns, count)
}
fun selectListByMap(tableName: String?, whereColumns: Map<String?, Any?>?, count: Int): List<Row> {
return Db.selectListByMap(tableName, whereColumns, count)
}
fun selectListByCondition(schema: String?, tableName: String?, condition: QueryCondition?): List<Row> {
return Db.selectListByCondition(schema, tableName, condition)
}
fun selectListByCondition(tableName: String?, condition: QueryCondition?): List<Row> {
return Db.selectListByQuery(
null as String?, tableName, QueryWrapper()
.where(condition)
)
}
fun selectListByCondition(schema: String?, tableName: String?, condition: QueryCondition?, count: Int): List<Row> {
return Db.selectListByQuery(
schema, tableName, QueryWrapper()
.where(condition).limit(count)
)
}
fun selectListByCondition(tableName: String?, condition: QueryCondition?, count: Int): List<Row> {
return Db.selectListByQuery(
null as String?, tableName, QueryWrapper()
.where(condition).limit(count)
)
}
fun selectListByQuery(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): List<Row> {
return Db.selectListByQuery(schema, tableName, queryWrapper)
}
fun selectListByQuery(tableName: String?, queryWrapper: QueryWrapper?): List<Row> {
return Db.selectListByQuery(null as String?, tableName, queryWrapper)
}
fun selectListByQuery(queryWrapper: QueryWrapper?): List<Row> {
return Db.selectListByQuery(queryWrapper)
}
fun selectAll(schema: String?, tableName: String?): List<Row> {
return Db.selectAll(schema, tableName)
}
fun selectAll(tableName: String?): List<Row> {
return Db.selectAll(null as String?, tableName)
}
fun selectObject(sql: String?, vararg args: Any?): Any {
return Db.selectObject(sql, *args)
}
fun selectObject(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): Any {
return Db.selectObject(schema, tableName, queryWrapper)
}
fun selectObject(tableName: String?, queryWrapper: QueryWrapper?): Any {
return Db.selectObject(null as String?, tableName, queryWrapper)
}
fun selectObject(queryWrapper: QueryWrapper?): Any {
return Db.selectObject(queryWrapper)
}
fun selectObjectList(sql: String?, vararg args: Any?): List<Any> {
return Db.selectObjectList(sql, *args)
}
fun selectObjectList(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): Any {
return Db.selectObjectList(schema, tableName, queryWrapper)
}
fun selectObjectList(tableName: String?, queryWrapper: QueryWrapper?): Any {
return Db.selectObjectList(tableName, queryWrapper)
}
fun selectObjectList(queryWrapper: QueryWrapper?): Any {
return Db.selectObjectList(queryWrapper)
}
fun selectCount(sql: String?, vararg args: Any?): Long {
return Db.selectCount(sql, *args)
}
fun selectCountByCondition(schema: String?, tableName: String?, condition: QueryCondition?): Long {
return Db.selectCountByQuery(
schema, tableName, QueryWrapper()
.where(condition)
)
}
fun selectCountByCondition(tableName: String?, condition: QueryCondition?): Long {
return Db.selectCountByCondition(
tableName, condition
)
}
fun selectCountByQuery(schema: String?, tableName: String?, queryWrapper: QueryWrapper?): Long {
return Db.selectCountByQuery(schema, tableName, queryWrapper)
}
fun selectCountByQuery(tableName: String?, queryWrapper: QueryWrapper?): Long {
return Db.selectCountByQuery(null as String?, tableName, queryWrapper)
}
fun selectCountByQuery(queryWrapper: QueryWrapper?): Long = Db.selectCountByQuery(queryWrapper)
fun paginate(
schema: String?,
tableName: String?,
pageNumber: Int,
pageSize: Int,
condition: QueryCondition?
): Page<Row> = Db.paginate(schema, tableName, Page(pageNumber, pageSize), QueryWrapper.create().where(condition))
fun paginate(tableName: String?, pageNumber: Int, pageSize: Int, condition: QueryCondition?): Page<Row> =
Db.paginate(tableName, pageNumber, pageSize, condition)
fun paginate(
schema: String?,
tableName: String?,
pageNumber: Int,
pageSize: Int,
totalRow: Int,
condition: QueryCondition?
): Page<Row> {
return Db.paginate(
schema, tableName, pageNumber, pageSize, totalRow, condition
)
}
fun paginate(
tableName: String?,
pageNumber: Int,
pageSize: Int,
totalRow: Int,
condition: QueryCondition?
): Page<Row> = Db.paginate(tableName, pageNumber, pageSize, totalRow, condition)
fun paginate(
schema: String?,
tableName: String?,
pageNumber: Int,
pageSize: Int,
queryWrapper: QueryWrapper?
): Page<Row> = Db.paginate(schema, tableName, pageNumber, pageSize, queryWrapper)
fun paginate(tableName: String?, pageNumber: Int, pageSize: Int, queryWrapper: QueryWrapper?): Page<Row> =
Db.paginate(tableName, pageNumber, pageSize, queryWrapper)
fun paginate(
schema: String?,
tableName: String?,
pageNumber: Int,
pageSize: Int,
totalRow: Int,
queryWrapper: QueryWrapper?
): Page<Row> {
return Db
.paginate(schema, tableName, pageNumber, pageSize, totalRow, queryWrapper)
}
fun paginate(
tableName: String?,
pageNumber: Int,
pageSize: Int,
totalRow: Int,
queryWrapper: QueryWrapper?
): Page<Row> {
return Db
.paginate(tableName, pageNumber, pageSize, totalRow, queryWrapper)
}
fun paginate(schema: String?, tableName: String?, page: Page<Row?>?, queryWrapper: QueryWrapper?): Page<Row> {
return Db.paginate(schema, tableName, page, queryWrapper)
}
fun paginate(tableName: String?, page: Page<Row?>?, queryWrapper: QueryWrapper?): Page<Row> {
return Db.paginate(tableName, page, queryWrapper)
}
fun tx(supplier: Supplier<Boolean?>?): Boolean {
return tx(supplier, Propagation.REQUIRED)
}
fun tx(supplier: Supplier<Boolean?>?, propagation: Propagation?): Boolean {
return Db.tx(supplier, propagation)
}
fun <T> txWithResult(supplier: Supplier<T>?): T {
return txWithResult(supplier, Propagation.REQUIRED)
}
fun <T> txWithResult(supplier: Supplier<T>?, propagation: Propagation?): T {
return Db.txWithResult(supplier, propagation)
}
}

View File

@ -0,0 +1,85 @@
package com.mybatisflex.kotlin.extend.entry
import com.mybatisflex.core.FlexConsts
import com.mybatisflex.core.dialect.DialectFactory
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.row.Row
import com.mybatisflex.core.row.RowUtil
import com.mybatisflex.core.table.TableDef
import com.mybatisflex.core.table.TableInfoFactory
import com.mybatisflex.core.util.ArrayUtil
import com.mybatisflex.kotlin.entry.Entry
import com.mybatisflex.kotlin.extend.db.DB
import com.mybatisflex.kotlin.scope.QueryScope
import java.util.Arrays
/*
* 实体操作扩展
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
infix fun <T> Row.to(entryClass: Class<T>): T {
return RowUtil.toEntity(this, entryClass)
}
inline fun <reified E, T : TableDef> T.filter(
vararg columns: QueryColumn?,
init: T.() -> QueryCondition
): List<E> {
val tableInfo = TableInfoFactory.ofEntityClass(E::class.java)
return DB.filter<E>(
columns = columns,
schema = tableInfo.schema,
tableName = tableInfo.tableName,
queryCondition = init()
)
}
inline fun <reified E> TableDef.query(
vararg columns: QueryColumn?,
noinline init: QueryScope.() -> Unit
): List<E> {
return DB.query<E>(
columns = columns,
schema = this.schema,
tableName = this.tableName,
init = init
)
}
inline fun <reified E> TableDef.all(
vararg columns: QueryColumn?
): List<E> = DB.selectAll(schema, tableName).toEntities()
inline fun <reified E> Collection<Row>.toEntities() = map { it to E::class.java }.toList()
inline fun<reified E:Entry> List<E>.batchInsert(): Boolean {
val entities = this
val tableInfo = TableInfoFactory.ofEntityClass(E::class.java)
for (entity in entities) {
tableInfo.initVersionValueIfNecessary(entity)
tableInfo.initTenantIdIfNecessary(entity)
tableInfo.initLogicDeleteValueIfNecessary(entity)
//执行 onInsert 监听器
tableInfo.invokeOnInsertListener(entity)
}
var allValues = FlexConsts.EMPTY_ARRAY
for (entity in entities) {
allValues = ArrayUtil.concat(allValues, tableInfo.buildInsertSqlArgs(entity, false))
}
val sql = DialectFactory.getDialect().forInsertEntityBatch(tableInfo, entities)
return DB.insertBySql(sql,*allValues) > 1
}
fun< E:Entry> List<E>.batchUpdate(): Boolean = all(Entry::update)
inline fun<reified E:Entry> List<E>. batchDeleteById(): Boolean {
val tableInfo = TableInfoFactory.ofEntityClass(E::class.java)
val primaryValues = this.map { tableInfo.buildPkSqlArgs(it) }.stream().flatMap(Arrays::stream).toArray()
val tenantIdArgs = tableInfo.buildTenantIdArgs()
val sql = DialectFactory.getDialect().forDeleteEntityBatchByIds(tableInfo, primaryValues)
return DB.deleteBySql(sql,*ArrayUtil.concat(primaryValues, tenantIdArgs)) > 1
}

View File

@ -0,0 +1,22 @@
package com.mybatisflex.kotlin.extend.mapper
import com.mybatisflex.core.BaseMapper
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.kotlin.scope.QueryScope
import com.mybatisflex.kotlin.scope.queryScope
/*
* 映射器操作扩展
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
fun <T> BaseMapper<*>.queryList(init: (QueryScope.() -> Unit)? = null): List<T> =
this.selectListByQuery(queryScope(init = init)) as List<T>
fun <T> BaseMapper<T>.update(entity: T, init: () -> QueryCondition): Int =
this.updateByCondition(entity, init())
fun <T> BaseMapper<T>.delete(init: (QueryScope.() -> Unit)? = null): Int =
this.deleteByQuery(queryScope(init = init))
fun <T> BaseMapper<T>.delete1(init: () -> QueryCondition): Int =
this.deleteByCondition(init())

View File

@ -0,0 +1,59 @@
package com.mybatisflex.kotlin.extend.sql
import com.mybatisflex.core.query.Joiner
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.query.QueryWrapper
import java.util.function.Consumer
/*
* sql操作扩展
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
infix fun QueryColumn.eq(value: Any?): QueryCondition {
return this.eq(value)
}
inline fun QueryCondition.andIf(test: Boolean, block: () -> QueryCondition): QueryCondition {
if (test) {
this.and(block())
}
return this
}
inline fun QueryCondition.orIf(test: Boolean, block: () -> QueryCondition): QueryCondition {
if (test) {
this.or(block())
}
return this
}
inline fun `if`(test: Boolean, block: () -> QueryCondition): QueryCondition {
if (test) {
return block()
}
return QueryCondition.createEmpty()
}
infix fun QueryColumn.like(value: String): QueryCondition = this.like(value)
infix fun QueryCondition.and(other: QueryCondition): QueryCondition = this.and(other)
infix fun QueryCondition.or(other: QueryCondition): QueryCondition = this.or(other)
infix fun QueryColumn.`=`(value: Any?): QueryCondition = this.eq(value)
infix fun QueryColumn.`in`(value: Collection<Any>): QueryCondition = this.`in`(value)
fun QueryColumn.`in`(vararg values: Array<Any>): QueryCondition = this.`in`(values.asList())
infix fun QueryWrapper.`as`(alias: String) = this.`as`(alias)
infix fun <M> Joiner<M>.`as`(alias: String?): Joiner<M> = this.`as`(alias)
infix fun <M> Joiner<M>.on(on: String?): M = this.on(on)
infix fun <M> Joiner<M>.on(on: QueryCondition?): M = this.on(on)
infix fun <M> Joiner<M>.on(consumer: Consumer<QueryWrapper?>): M = this.on(consumer)

View File

@ -0,0 +1,45 @@
package com.mybatisflex.kotlin.scope
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.core.table.TableDef
/**
* 查询作用域
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
class QueryScope :QueryWrapper() {
companion object CurrentQueryScope : ThreadLocal<QueryScope>()
fun from(init: (QueryScope.() -> Unit)? = null): QueryWrapper = this.from(queryScope(init = init))
fun <T : TableDef> where(tableDef: T, build: T.() -> QueryCondition): QueryWrapper = this.where(build(tableDef))
fun where(build: QueryScope.() -> QueryCondition): QueryWrapper = this.where(build(this))
operator fun String.get(name: String): QueryColumn = QueryColumn(this, name)
operator fun String.unaryMinus(): QueryColumn = QueryColumn(this)
}
fun queryScope(vararg columns: QueryColumn?, init: (QueryScope.() -> Unit)? = null): QueryWrapper {
val builder = QueryScope()
if (columns.isNotEmpty()) {
builder.select(columns)
}
//用于嵌套查询拿到上层查询包装对象
init?.also {
val prentQueryScope = QueryScope.get()
QueryScope.set(builder)
it(builder)
QueryScope.set(prentQueryScope)
}
return builder
}

View File

@ -0,0 +1,76 @@
package com.myba
import com.mybatisflex.kotlin.extend.entry.batchDeleteById
import com.mybatisflex.core.BaseMapper
import com.mybatisflex.core.MybatisFlexBootstrap
import com.mybatisflex.core.audit.AuditManager
import com.mybatisflex.core.audit.ConsoleMessageCollector
import com.mybatisflex.kotlin.entry.Entry
import com.mybatisflex.kotlin.extend.db.DB
import com.mybatisflex.kotlin.extend.db.DB.filter
import com.mybatisflex.kotlin.extend.entry.all
import com.mybatisflex.kotlin.extend.entry.batchInsert
import com.mybatisflex.kotlin.extend.entry.batchUpdate
import com.mybatisflex.kotlin.extend.mapper.queryList
import com.mybatisflex.kotlin.extend.sql.*
import com.mybatisflex.kotlintest.entry.Account
import com.mybatisflex.kotlintest.entry.table.AccountTableDef.ACCOUNT
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType
import javax.sql.DataSource
import kotlin.streams.toList
fun main() {
val dataSource: DataSource = EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.addScript("data.sql")
.build()
AuditManager.setAuditEnable(true);
AuditManager.setMessageCollector(ConsoleMessageCollector())
MybatisFlexBootstrap.getInstance()
.addMapper(AccountMapper::class.java)
.setDataSource(dataSource)
.start()
filter<Account> {
ACCOUNT.AGE `=` 12 or
`if`(true) { ACCOUNT.ID `in` listOf(1, 2) }
}.stream().peek(::println).peek { it.id = it.id!!.plus(2) }.forEach(Entry::save)
println("保存后————————")
DB.mapper<AccountMapper>().findByAge(18,1,2).stream().peek { println(it) }.forEach(Entry::deleteById)
println("删除后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.map { it.userName = "sa"
it }.forEach(Entry::update)
println("更新后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.map {
it.id = it.id!!.plus(5)
it.userName = "423423"
it }.toList().batchInsert()
println("批量插入后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.toList().filter { it.id!!.rem(2) == 0 }.batchDeleteById()
println("批量删除后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.toList().filter { it.id!!.rem(3) == 0 }.map { it.userName = "哈哈"
it }.batchUpdate()
println("批量更新后————————")
ACCOUNT.all<Account>().stream().forEach { println(it) }
}
@JvmDefaultWithCompatibility
interface AccountMapper : BaseMapper<Account> {
fun findByAge(age: Int, vararg ids: Int): List<Account> = queryList {
select(ACCOUNT.ALL_COLUMNS)
from(ACCOUNT)
where(ACCOUNT) {
(AGE `=` age) and `if`(true) {
ID `in` ids.asList()
}
}
}
}

View File

@ -0,0 +1,25 @@
package com.mybatisflex.kotlintest.entry
import com.mybatisflex.annotation.Column
import com.mybatisflex.annotation.Id
import com.mybatisflex.annotation.NoneListener
import com.mybatisflex.annotation.Table
import com.mybatisflex.kotlin.entry.Entry
import java.util.*
/**
* 测试用数据类最好不要写成data class否则需要与数据库字段数据顺序一致
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
@Table(value = "tb_account", onUpdate = [NoneListener::class])
data class Account(
@Id var id: Int?,
@Column("u_name") var userName: String?,
var age: Int?,
var birthday: Date?,
) : Entry(){
override fun toString(): String {
return "Account(id=$id, userName=$userName, birthday=$birthday, age=$age)"
}
}

View File

@ -0,0 +1,4 @@
INSERT INTO tb_account
VALUES (1, 'Michael Yang', 18, '2020-01-11');
INSERT INTO tb_account
VALUES (2, 'Michael Zhanng', 20, '2020-01-11');

View File

@ -0,0 +1,4 @@
processor.mappersGenerateEnable=false
processor.tablesNameStyle=upCase
processor.tablesDefSuffix=Def
processor.allInTables=true

View File

@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS `tb_account`
(
`id` INTEGER PRIMARY KEY,
`u_name` VARCHAR(100) NOT NULL,
`age` INTEGER,
`birthday` DATETIME
);
CREATE TABLE IF NOT EXISTS `tb_account1`
(
`id` INTEGER PRIMARY KEY,
`u_name` VARCHAR(100) NOT NULL,
`age` INTEGER,
`birthday` DATETIME
);

View File

@ -48,6 +48,7 @@
<module>mybatis-flex-solon-plugin</module>
<module>mybatis-flex-test</module>
<module>mybatis-flex-processor</module>
<module>mybatis-flex-kotlin</module>
</modules>
<properties>