Spring Boot Mybatis++ 2025详解

 更新时间:2025年02月05日 09:25:01   作者:ByteFlys  
文章介绍了三种基于注解SQL和查询接口的MyBatis使用方式,讨论了Entity和Example的区别,即Entity会更新所有字段,而Example仅更新非空字段,感兴趣的朋友一起看看吧

Structure

this blog introduce 3 ways using mybatis

  • based on annotationed SQL and Query interfaces : suppored by MyBatis framework
  • based on Query Wrapper : supported by MyBatis Plus framework
  • MyBatis Plus provides a easier way to dynamically set condition and updated fields
  • base on Query Condition : combined MyBatis Plus and Kotlin, so called MyBatis++
  • MyBatis++ provides a more easier way to build complicated conditions
  • and supports update values through an Example bean

MyBatis++ Controller Abilities

this controller present multiple ways to do CURD with MyBatis++

you can choose your favorite ones or those match your current project most comfortably

package x.spring.hello.controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import x.kotlin.commons.serialize.JSON.toJson
import x.kotlin.commons.serialize.JSON.toJsonOrNull
import x.kotlin.commons.string.UUID
import x.spring.hello.model.User
import x.spring.hello.model.UserExample
import x.spring.hello.repository.UserMapper
import x.spring.hello.mybatis.*
@RestController
class UserController {
    @Autowired
    private lateinit var userMapper: UserMapper
    @GetMapping("/01")
    fun selectAll(): String {
        val userList = userMapper.selectAll()
        return userList.toJson()
    }
    @GetMapping("/02")
    fun selectByName(): String {
        val user = userMapper.selectUserByName("Jimmy")
        return user.toJsonOrNull().orEmpty()
    }
    @GetMapping("/03")
    fun selectByCondition(): String {
        val condition = condition { it.eq(User::name, "Jimmy") }
        val users = userMapper.selectList(condition.build())
        return users.toJson()
    }
    @GetMapping("/04")
    fun insert(): String {
        val user = User()
        user.name = UUID.short()
        userMapper.insert(user)
        return user.toJson()
    }
    @GetMapping("/05")
    fun insertOrUpdate(): String {
        val user = User()
        user.id = "1"
        user.name = UUID.short()
        userMapper.insertOrUpdate(user)
        return user.toJson()
    }
    @GetMapping("/06")
    fun updateByCondition(): String {
        val cond1 = condition { it.isNotNull(User::id) }
        val cond2 = condition { it.eq(User::name, "Jimmy") }
        val cond3 = condition { it.gt(User::age, 15) }
        val cond4 = condition {
            it.set(User::name, "Jimmy")
            it.set(User::age, 18)
        }
        val condition = cond1 and cond2 and cond3 attributes cond4
        val count = userMapper.update(condition.build())
        return count.toJson()
    }
    @GetMapping("/07")
    fun updateByEntityAndCondition(): String {
        val entity = User()
        entity.name = "Updated"
        entity.age = 36
        val cond1 = condition { it.isNotNull(User::id) }
        val cond2 = condition { it.like(User::name, "Jimmy") }
        val cond3 = condition { it.gt(User::age, 35) }
        val condition = cond1 and (cond2 or cond3)
        val count = userMapper.update(entity, condition.build())
        return count.toJson()
    }
    @GetMapping("/08")
    fun updateByExampleAndCondition(): String {
        val example = UserExample()
        example.age = 18
        val cond1 = condition { it.isNotNull(User::id) }
        val cond2 = condition { it.like(User::name, "Jimmy") }
        val cond3 = condition { it.gt(User::age, 35) }
        val condition = cond1 and (cond2 or cond3) values example
        val count = userMapper.update(condition.build())
        return count.toJson()
    }
    @GetMapping("/09")
    fun selectCrossTables(): String {
        val userRoles = userMapper.selectUserRole()
        return userRoles.toJson()
    }
}

Configure Plugins and Repositories

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode = RepositoriesMode.PREFER_SETTINGS
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
buildscript {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
plugins {
    id("org.jetbrains.kotlin.jvm") version "2.0.21" apply false
    id("org.jetbrains.kotlin.kapt") version "2.0.21" apply false
    id("org.jetbrains.kotlin.plugin.spring") version "2.0.21" apply false
    id("org.springframework.boot") version "3.4.1" apply false
}
include("spring-mybatis")

Apply Plugins and Add Dependencies

plugins {
    id("org.jetbrains.kotlin.jvm")
    id("org.jetbrains.kotlin.kapt")
    id("org.jetbrains.kotlin.plugin.spring")
    id("org.springframework.boot")
}
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}
dependencies {
    val springBootVersion = "3.4.1"
    val springCloudVersion = "4.2.0"
    val springCloudAlibabaVersion = "2023.0.3.2"
    // commons
    api("io.github.hellogoogle2000:kotlin-commons:1.0.19")
    // kotlin
    api("org.jetbrains.kotlin:kotlin-reflect:2.0.21")
    // spring
    api("org.springframework.boot:spring-boot-starter:$springBootVersion")
    api("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
    api("org.springframework.cloud:spring-cloud-starter-bootstrap:$springCloudVersion")
    // mybatis
    api("link.thingscloud:quick-spring-boot-starter-mybatis-plus:2025.01.22")
}

MyBatis++ Spring Properties

# service
server.port=10003
spring.application.name=mybatis
spring.profiles.active=dev
spring.devtools.add-properties=false
# mybatis
spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.url=jdbc:mysql://localhost:3306/dev?characterEncoding=utf-8&serverTimezone=UTC

MyBatis++ Application

package x.spring.hello
import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
@MapperScan(basePackages = ["x.spring.hello.repository"])
class MybatisApplication
fun main(args: Array<String>) {
    runApplication<MybatisApplication>(*args)
}

MyBatis++ Beans

package x.spring.hello.model
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
class User {
    @TableId(type = IdType.ASSIGN_UUID)
    var id = ""
    var name = ""
    var age = 0
}
package x.spring.hello.model
class UserExample {
    var id: String? = null
    var name: String? = null
    var age: Int? = null
}
package x.spring.hello.model
class UserRoleQueryResult {
    var name = ""
    var role = ""
}

MyBatis++ Mapper

mapper sometimes called interface, service or repository in other projects

package x.spring.hello.repository
import link.thingscloud.quick.mybatisplus.base.BaseMapper
import org.apache.ibatis.annotations.Select
import x.spring.hello.model.User
import x.spring.hello.model.UserRoleQueryResult
interface UserMapper : BaseMapper<User> {
    @Select("select * from user")
    fun selectAll(): MutableList<User>
    @Select("select * from user where name = #{name}")
    fun selectUserByName(name: String): User?
    @Select(
        """
          select 
            user.name as name,
            role.name as role 
          from user left join role
          on user.roleId = role.id
        """
    )
    fun selectUserRole(): List<UserRoleQueryResult>
}

MyBatis++ Query Builder

this is the core component to build query condition and examples

difference between entity and example is :

entity will update all field, while example only update non-null fields

package x.spring.hello.mybatis
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
fun interface ConditionConfigurator<T : Any> {
    fun configure(wrapper: KtUpdateWrapper<T>)
}
data class QueryCondition<T : Any>(
    val configurator: ConditionConfigurator<T>
)
inline fun <reified T : Any> QueryCondition<T>.build(): KtUpdateWrapper<T> {
    val wrapper = KtUpdateWrapper(T::class.java)
    configurator.configure(wrapper)
    return wrapper
}
inline fun <reified T : Any> condition(configurator: ConditionConfigurator<T>): QueryCondition<T> {
    return QueryCondition(configurator)
}
infix fun <T : Any> QueryCondition<T>.and(other: QueryCondition<T>): QueryCondition<T> {
    val configurator = ConditionConfigurator {
        configurator.configure(it)
        it.and { other.configurator.configure(it) }
    }
    return QueryCondition(configurator)
}
infix fun <T : Any> QueryCondition<T>.or(other: QueryCondition<T>): QueryCondition<T> {
    val configurator = ConditionConfigurator {
        configurator.configure(it)
        it.or { other.configurator.configure(it) }
    }
    return QueryCondition(configurator)
}
infix fun <T : Any> QueryCondition<T>.not(other: QueryCondition<T>): QueryCondition<T> {
    val configurator = ConditionConfigurator {
        configurator.configure(it)
        it.not { other.configurator.configure(it) }
    }
    return QueryCondition(configurator)
}
infix fun <T : Any> QueryCondition<T>.attributes(other: QueryCondition<T>): QueryCondition<T> {
    val configurator = ConditionConfigurator {
        configurator.configure(it)
        other.configurator.configure(it)
    }
    return QueryCondition(configurator)
}
inline infix fun <reified T : Any, reified S : Any> QueryCondition<T>.values(example: S): QueryCondition<T> {
    val configurator = ConditionConfigurator { wrapper ->
        configurator.configure(wrapper)
        val properties = S::class.memberProperties
        properties.forEach { propertyS ->
            val value = propertyS.get(example)
            value.takeIf { it != null } ?: return@forEach
            val property = T::class.findPropertyByName(propertyS.name)
            property.takeIf { it != null } ?: return@forEach
            wrapper.set(property, value)
        }
    }
    return QueryCondition(configurator)
}
inline fun <reified T : Any> KClass<T>.findPropertyByName(name: String): KProperty1<T, *>? {
    return memberProperties.firstOrNull { it.name == name }
}

到此这篇关于Spring Boot Mybatis++ 2025的文章就介绍到这了,更多相关Spring Boot Mybatis++ 2025内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java Semaphore实现高并发场景下的流量控制

    Java Semaphore实现高并发场景下的流量控制

    在java开发的工作中是否会出现这样的场景,你需要实现一些异步运行的任务,该任务可能存在消耗大量内存的情况,所以需要对任务进行并发控制。本文将介绍通过Semaphore类优雅的实现并发控制,感兴趣的可以了解一下
    2021-12-12
  • Java中关于OAuth2.0的原理分析

    Java中关于OAuth2.0的原理分析

    这篇文章主要介绍了Java中关于OAuth2.0的原理分析,OAuth是一个关于授权的开放网络标准,允许用户授权第三 方应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,需要的朋友可以参考下
    2023-09-09
  • 详解springboot接口如何优雅的接收时间类型参数

    详解springboot接口如何优雅的接收时间类型参数

    这篇文章主要为大家详细介绍了springboot的接口如何优雅的接收时间类型参数,文中为大家整理了三种常见的方法,希望对大家有一定的帮助
    2023-09-09
  • struts2实现多文件上传

    struts2实现多文件上传

    这篇文章主要为大家详细介绍了struts2实现多文件上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08
  • Java多线程编程详细解释

    Java多线程编程详细解释

    这篇文章主要介绍了java多线程编程实例,分享了几则多线程的实例代码,具有一定参考价值,加深多线程编程的理解还是很有帮助的,需要的朋友可以参考下。
    2021-11-11
  • Java单例模式利用HashMap实现缓存数据

    Java单例模式利用HashMap实现缓存数据

    这篇文章主要为大家详细介绍了Java单例模式利用HashMap实现缓存数据,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • SpringBoot使用Scheduling实现定时任务的示例代码

    SpringBoot使用Scheduling实现定时任务的示例代码

    Spring Boot提供了一种方便的方式来实现定时任务,即使用Spring的@Scheduled注解,通过在方法上添加@Scheduled注解,我们可以指定方法在何时执行,本文我们就给大家介绍一下SpringBoot如何使用Scheduling实现定时任务,需要的朋友可以参考下
    2023-08-08
  • springboot部署linux访问服务器资源的方法

    springboot部署linux访问服务器资源的方法

    这篇文章主要介绍了springboot部署linux访问服务器资源,部署springboot项目至服务器用了几种不同方法,文中给大家详细介绍,需要的朋友可以参考下
    2019-12-12
  • 解决执行maven命令时提示Process terminated的问题

    解决执行maven命令时提示Process terminated的问题

    这篇文章主要介绍了解决执行maven命令时提示Process terminated的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • JAVA得到数组中最大值和最小值的简单实例

    JAVA得到数组中最大值和最小值的简单实例

    这篇文章主要介绍了JAVA得到数组中最大值和最小值的简单实例,需要的朋友可以参考下
    2014-08-08

最新评论