This commit is contained in:
开源海哥 2023-08-17 10:07:00 +08:00
parent de62e0a8a0
commit 468bfa706d
22 changed files with 3 additions and 1133 deletions

View File

@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mybatis-flex</groupId>
<artifactId>parent</artifactId>
<version>1.5.7</version>
</parent>
<artifactId>mybatis-flex-kotlin</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<kotlin.version>1.9.0</kotlin.version>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-core</artifactId>
<version>${mybatis-flex.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<configuration>
<args>
<arg>-Xjvm-default=all</arg>
</args>
</configuration>
<executions>
<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,3 @@
# MyBatis-Flex-Kotlin
模块以迁移至https://gitee.com/mybatis-flex/mybatis-flex-kotlin

View File

@ -1,55 +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.kotlin.db
import java.util.NoSuchElementException
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 && init != null) {
synchronized(this) {
if (_value == null) {
_value = init?.invoke()
//释放引用
init = null
}
}
}
return this._value?:throw NoSuchElementException()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
_value = value
}
}

View File

@ -1,110 +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.kotlin.extensions.db
import com.mybatisflex.core.mybatis.Mappers
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.row.Db.selectListByQuery
import com.mybatisflex.core.row.Db.selectOneByQuery
import com.mybatisflex.core.row.Row
import com.mybatisflex.core.table.TableDef
import com.mybatisflex.core.table.TableInfoFactory
import com.mybatisflex.kotlin.extensions.model.filter
import com.mybatisflex.kotlin.extensions.model.toEntities
import com.mybatisflex.kotlin.scope.QueryScope
import com.mybatisflex.kotlin.scope.queryScope
/*
* 数据库简单操作扩展
* @author 卡莫sama(yuanjiashuai)
*/
inline fun <reified M > mapper(): M = Mappers.ofMapperClass(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,
tableName,
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<T>()
fun queryRows(
vararg columns: QueryColumn?,
schema: String? = null,
tableName: String? = null,
init: QueryScope.() -> Unit
): List<Row> = selectListByQuery(
schema,tableName,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<E>()
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)

View File

@ -1,35 +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.kotlin.extensions.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)
*/
fun <T> BaseMapper<*>.queryList(init: (QueryScope.() -> Unit)?): 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)?): Int =
this.deleteByQuery(queryScope(init = init))

View File

@ -1,79 +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.kotlin.extensions.model
import com.mybatisflex.core.activerecord.Model
import com.mybatisflex.core.mybatis.Mappers
import com.mybatisflex.core.query.QueryColumn
import com.mybatisflex.core.query.QueryCondition
import com.mybatisflex.core.row.Db.*
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.SqlUtil
import com.mybatisflex.kotlin.extensions.db.*
import com.mybatisflex.kotlin.scope.QueryScope
import java.io.Serializable
/*
* 实体操作扩展
* @author 卡莫sama(yuanjiashuai)
*/
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 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 query<E>(
columns = columns,
schema = this.schema,
tableName = this.tableName,
init = init
)
}
inline fun <reified E> TableDef.all(): List<E> = selectAll(schema, tableName).toEntities<E>()
inline fun <reified E> Collection<Row>.toEntities() = map { it to E::class.java }.toList()
inline fun<reified E:Model<E>> List<E>.batchInsert(): Int = Mappers.ofEntityClass<E>(E::class.java).insertBatch(this)
fun< E:Model<E>> List<E>.batchUpdateById(): Boolean = all(Model<E>::updateById)
inline fun<reified E:Model<E>> List<E>. batchDeleteById(): Boolean {
//拿到集合中所有实体的主键
val primaryValues = this.map { it.pkValues() }.flatMap(Array<*>::toMutableList).map { it as Serializable }
return SqlUtil.toBool(Mappers.ofEntityClass<E>(E::class.java).deleteBatchByIds(primaryValues))
}

View File

@ -1,109 +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.kotlin.extensions.sql
import com.mybatisflex.core.query.*
import java.util.function.Consumer
/*
* sql操作扩展
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
//logic------
inline fun `if`(test: Boolean, block: () -> QueryCondition): QueryCondition =
if (test) block() else QueryCondition.createEmpty()
inline fun QueryCondition.andIf(test: Boolean, block: () -> QueryCondition): QueryCondition =
if (test) this.and(block()) else this
inline fun QueryCondition.orIf(test: Boolean, block: () -> QueryCondition): QueryCondition =
if (test) this.or(block()) else this
infix fun QueryCondition.and(other: QueryCondition): QueryCondition = this.and(other)
infix fun QueryCondition.or(other: QueryCondition): QueryCondition = this.or(other)
//Comparable------
infix fun QueryColumn.like(value: String): QueryCondition = this.like(value)
infix fun QueryColumn.eq(value: Any?): QueryCondition = this.eq(value)
infix fun QueryColumn.ne(value: Any?): QueryCondition = this.ne(value)
infix fun QueryColumn.`=`(value: Any?): QueryCondition = this.eq(value)
infix fun QueryColumn.`!=`(value: Any?): QueryCondition = this.ne(value)
infix fun QueryColumn.gt(value: Any?): QueryCondition = this.gt(value)
infix fun QueryColumn.ge(value: Any?): QueryCondition = this.ge(value)
infix fun QueryColumn.le(value: Any?): QueryCondition = this.le(value)
infix fun QueryColumn.lt(value: Any?): QueryCondition = this.lt(value)
//range-----
infix fun QueryColumn.between(pair: Pair<Any?, Any?>): QueryCondition = this.between(pair.first, pair.second)
infix fun QueryColumn.notBetween(pair: Pair<Any?, Any?>): QueryCondition = this.notBetween(pair.first, pair.second)
infix fun QueryColumn.between(range: ClosedRange<*>): QueryCondition = this.between(range.start, range.endInclusive)
infix fun QueryColumn.notBetween(range: ClosedRange<*>): QueryCondition =
this.notBetween(range.start, range.endInclusive)
infix fun QueryColumn.notIn(value: Collection<Any?>): QueryCondition = this.notIn(value)
infix fun QueryColumn.notIn(values: Array<Any?>): QueryCondition = this.notIn(values)
infix fun QueryColumn.`in`(value: Collection<Any?>): QueryCondition = this.`in`(value)
infix fun QueryColumn.`in`(values: Array<Any?>): QueryCondition = this.`in`(values)
infix fun QueryColumn.`in`(range: IntRange): QueryCondition = this.`in`(range.toList())
//as-----
infix fun QueryWrapper.`as`(alias: String?) = this.`as`(alias)
//join------
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)
// orderBy------
infix fun QueryWrapper.orderBy(orderBys: Collection<QueryOrderBy?>): QueryWrapper =
this.orderBy(*orderBys.toTypedArray())
infix fun QueryWrapper.orderBy(orderBy: QueryOrderBy?): QueryWrapper = this.orderBy(orderBy)
operator fun QueryColumn.unaryPlus(): QueryOrderBy = this.asc()
operator fun QueryColumn.unaryMinus(): QueryOrderBy = this.desc()
// limit------
infix fun QueryWrapper.limit(rows: Number): QueryWrapper = this.limit(rows)
infix fun QueryWrapper.limit(pair: Pair<Number?, Number?>): QueryWrapper = this.limit(pair.first, pair.second)
infix fun QueryWrapper.limit(range: IntRange): QueryWrapper = this.limit(range.first, range.last)

View File

@ -1,58 +0,0 @@
package com.mybatisflex.kotlin.scope
/*
* 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.
*/
import com.mybatisflex.core.MybatisFlexBootstrap
import javax.sql.DataSource
class BootstrapScope(private val instant: MybatisFlexBootstrap = MybatisFlexBootstrap.getInstance()) {
fun dataSources(dataSourceScope: DataSourceScope.() -> Unit) =
dataSourceScope(DataSourceScope(instant))
operator fun <T> Class<T>.unaryPlus(): MybatisFlexBootstrap =
instant.addMapper(this)
operator fun DataSource.unaryPlus(): MybatisFlexBootstrap =
instant.setDataSource(this)
infix fun String.of(dataSource: DataSource): MybatisFlexBootstrap =
instant.setDataSource(this, dataSource)
}
class DataSourceScope(private val bootstrap: MybatisFlexBootstrap) {
fun dataSource(dataSourceKey: String, dataSource: DataSource) =
bootstrap.addDataSource(dataSourceKey, dataSource)
}
fun buildBootstrap(
instant: MybatisFlexBootstrap = MybatisFlexBootstrap.getInstance(),
scope: BootstrapScope.(MybatisFlexBootstrap) -> Unit
): MybatisFlexBootstrap {
scope(BootstrapScope(instant), instant)
return instant
}

View File

@ -1,60 +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.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

@ -1,38 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

View File

@ -1,141 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-test</artifactId>
<version>1.5.7</version>
</parent>
<artifactId>mybatis-flex-spring-kotlin-test</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
<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-kotlin</artifactId>
<version>${mybatis-flex.version}</version>
</dependency>
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring</artifactId>
<version>${mybatis-flex.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.22.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<configuration>
<args>
<!--需要配置此项才能开启接口默认方法-->
<arg>-Xjvm-default=all</arg>
</args>
<compilerPlugins>
<!--适配数据类无无参构造问题-->
<plugin>no-arg</plugin>
</compilerPlugins>
<pluginOptions>
<option>no-arg:annotation=com.mybatisflex.annotation.Table</option>
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-sam-with-receiver</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>kapt</id>
<goals>
<goal>kapt</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
</sourceDirs>
<annotationProcessorPaths>
<!-- 在此处指定你的注解处理器。 -->
<annotationProcessorPath>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-processor</artifactId>
<version>${mybatis-flex.version}</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</execution>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,65 +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
import com.mybatisflex.core.mybatis.FlexConfiguration
import com.mybatisflex.spring.FlexSqlSessionFactoryBean
import org.apache.ibatis.logging.stdout.StdOutImpl
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.mybatis.spring.annotation.MapperScan
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.event.ContextStartedEvent
import org.springframework.context.event.EventListener
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType
import javax.sql.DataSource
@Configuration
@MapperScan("com.mybatisflex.test.mapper")
open class AppConfig {
@Bean
open fun dataSource(): DataSource? {
return EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.addScript("data-kt.sql")
.build()
}
@Bean
open fun sqlSessionFactory(dataSource: DataSource): SqlSessionFactory? {
val factoryBean: SqlSessionFactoryBean = FlexSqlSessionFactoryBean()
factoryBean.setDataSource(dataSource)
val configuration = FlexConfiguration()
configuration.logImpl = StdOutImpl::class.java
factoryBean.setConfiguration(configuration)
return factoryBean.getObject()
}
@EventListener(classes = [ContextStartedEvent::class])
open fun handleContextStartedEvent() {
println("handleContextStartedEvent listener invoked!")
}
}

View File

@ -1,40 +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.mapper
import com.mybatisflex.core.BaseMapper
import com.mybatisflex.kotlin.extensions.mapper.queryList
import com.mybatisflex.kotlin.extensions.sql.*
import com.mybatisflex.test.model.Account
@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`(ids.isNotEmpty()) {
ID `in` ids.asList()
}
}
}
}

View File

@ -1,42 +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.model
import com.mybatisflex.annotation.Id
import com.mybatisflex.annotation.NoneListener
import com.mybatisflex.annotation.Table
import com.mybatisflex.core.activerecord.Model
import com.mybatisflex.test.model.table.AccountTableDef
import java.util.*
/**
* 测试用数据类最好不要写成data class否则没有无参构造需要与数据库字段数据顺序一致
* @author 卡莫sama(yuanjiashuai)
* @date 2023/8/7
*/
@Table(value = "tb_account", onUpdate = [NoneListener::class], onSet = [AccountOnSetListener::class])
data class Account(
@Id var id: Int,
var userName: String?,
var age: Int?,
var birthday: Date?,
) : Model<Account>(){
companion object : AccountTableDef()
override fun toString(): String {
return "Account(id=$id, userName=$userName, birthday=$birthday, age=$age)"
}
}

View File

@ -1,27 +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.model
import com.mybatisflex.annotation.SetListener
class AccountOnSetListener : SetListener {
override fun onSet(entity: Any, property: String, value: Any): Any {
println(">>>>>>> property: $property value:$value")
return value
}
}

View File

@ -1,3 +0,0 @@
INSERT INTO tb_account(id, user_name, age, birthday)
VALUES (1, '张三', 18, '2020-01-11'),
(2, '李四', 19, '2021-03-21');

View File

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

View File

@ -1,7 +0,0 @@
CREATE TABLE IF NOT EXISTS `tb_account`
(
`id` INTEGER ,
`user_name` VARCHAR(100) NOT NULL,
`age` INTEGER,
`birthday` DATETIME
);

View File

@ -1,41 +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
import com.mybatisflex.test.mapper.AccountMapper
import org.assertj.core.api.WithAssertions
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import kotlin.test.Test
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = [AppConfig::class])
class KotlinSpringTest : WithAssertions {
@Autowired
lateinit var accountMapper: AccountMapper
@Test
fun testSelectByQuery() {
val accounts = accountMapper.findByAge(18,2)
accounts.forEach(::println)
}
}

View File

@ -1,145 +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
import com.mybatisflex.core.FlexConsts
import com.mybatisflex.core.activerecord.Model
import com.mybatisflex.core.audit.AuditManager
import com.mybatisflex.core.audit.ConsoleMessageCollector
import com.mybatisflex.kotlin.extensions.db.filter
import com.mybatisflex.kotlin.extensions.db.mapper
import com.mybatisflex.kotlin.extensions.db.query
import com.mybatisflex.kotlin.extensions.model.*
import com.mybatisflex.kotlin.extensions.sql.*
import com.mybatisflex.kotlin.scope.buildBootstrap
import com.mybatisflex.test.mapper.AccountMapper
import com.mybatisflex.test.model.Account
import com.mybatisflex.test.model.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
import kotlin.test.Test
class KotlinTest {
@Test
fun testDb() {
val dataSource: DataSource = EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.addScript("data-kt.sql")
.build()
AuditManager.setAuditEnable(true)
AuditManager.setMessageCollector(ConsoleMessageCollector())
buildBootstrap {
// 此方法体 it 是 MybatisFlexBootstrap 实例
// 配置Mapper
// 1.通过+(重写自增)的方式
+AccountMapper::class.java
// 2.通过原始的方式
// it.addMapper(AccountMapper::class.java)
// 配置单dataSource
// 1.通过+(重写自增)的方式
+dataSource
// 2.通过原始的方式
// it.setDataSource(dataSource)
// 配置多dataSource
// 1.通过of中缀的方式
FlexConsts.NAME of dataSource
// "dataSource1" of dataSource
// "dataSource2" of dataSource
// 2.通过dsl中缀的方式
dataSources {
// dataSource(FlexConsts.NAME,dataSource)
// dataSource("dataSource1",dataSource)
// dataSource("dataSource2",dataSource)
}
// 3.通过原始的方式
// it.addDataSource(FlexConsts.NAME,dataSource)
}.start()
// 查询表对象对应的所有实体数据
ACCOUNT.all<Account>().forEach(::println)
// ACCOUNT.query<Account> {}.forEach(::println)
// a and (b or c)
// filter:
filter<Account> {
ACCOUNT.ID `=` 1 and
(ACCOUNT.AGE `in` (17..19) or (ACCOUNT.BIRTHDAY between ("2020-01-10" to "2020-01-12")) )
}.forEach(::println)
// query:
query <Account> {
from(Account)
where(Account) {
(AGE `in` (17..19) or (BIRTHDAY between ("2020-01-10" .. "2020-01-12")) )
} orderBy -Account.ID
}.forEach(::println)
// 查询表对象对应的实体数据并根据条件过滤
filter<Account> {
ACCOUNT.AGE `=` 12 or
//if的第一个参数为true时则会调用花括号类的方法返回一个条件对象与上面那个条件对象相连接
`if`(true) { ACCOUNT.ID between (1 to 2) }
// `if`(false) { ACCOUNT.ID `in` listOf(1, 2) }
}.stream().peek(::println)
// 过滤后修改id再次保存
.peek { it.id = it.id.plus(2) }.forEach(Model<*>::save)
// 使用表对象filter或者DB对象有两个泛型的filter方法时方法体内this为表对象无需XXX.AA调用直接AA
// ACCOUNT.filter<Account,AccountTableDef> {
// AGE `=` 12 or
// `if`(true) { ID `in` listOf(1, 2) }
// }.stream().peek(::println).peek { it.id = it.id.plus(6) }.forEach(Entry::save)
println("保存后————————")
// 获得mapper实例通过自定义的默认方法查并将查到的删除
mapper<AccountMapper>().findByAge(18, 1, 2).stream().peek { println(it) }.forEach{it.removeById()}
println("删除后————————")
Account.all<Account>().stream().peek { println(it) }.map {
it.userName = "kamo"
it
}.forEach{it.updateById()}
println("更新后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.map {
it.id = it.id.plus(5)
it.userName = "akino"
it
}.toList().batchInsert()
println("批量插入后————————")
ACCOUNT.all<Account>().stream().peek { println(it) }.toList().filter { it.id.rem(2) == 0 }.batchDeleteById()
println("批量删除后————————")
//直接使用函数查询时需指定from表
query<Account> { from(ACCOUNT) }.stream().peek { println(it) }.toList().filter { it.id.rem(3) == 0 }.map {
it.userName = "cloud-player"
it
}.batchUpdateById()
println("批量更新后————————")
//使用表对象查询时无需指定from表
ACCOUNT.query<Account> {}.forEach(::println)
}
}

View File

@ -19,7 +19,6 @@
<module>mybatis-flex-spring-test</module>
<module>mybatis-flex-spring-boot-test</module>
<module>mybatis-flex-spring-cloud-test</module>
<module>mybatis-flex-spring-kotlin-test</module>
</modules>
<properties>

View File

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