[ Spring ] Spring Boot Mybatis++ 2025

文章目录

          • Structure
          • MyBatis++ Controller Abilities
          • Configure Plugins and Repositories
          • Apply Plugins and Add Dependencies
          • MyBatis++ Spring Properties
          • MyBatis++ Application
          • MyBatis++ Beans
          • MyBatis++ Mapper
          • MyBatis++ Query Builder

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.controllerimport 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 {@Autowiredprivate 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 cond4val count = userMapper.update(condition.build())return count.toJson()}@GetMapping("/07")fun updateByEntityAndCondition(): String {val entity = User()entity.name = "Updated"entity.age = 36val 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 = 18val 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 exampleval 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_SETTINGSrepositories {gradlePluginPortal()google()mavenCentral()}
}buildscript {repositories {gradlePluginPortal()google()mavenCentral()}
}plugins {id("org.jetbrains.kotlin.jvm") version "2.0.21" apply falseid("org.jetbrains.kotlin.kapt") version "2.0.21" apply falseid("org.jetbrains.kotlin.plugin.spring") version "2.0.21" apply falseid("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"// commonsapi("io.github.hellogoogle2000:kotlin-commons:1.0.19")// kotlinapi("org.jetbrains.kotlin:kotlin-reflect:2.0.21")// springapi("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")// mybatisapi("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.helloimport org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication@SpringBootApplication
@MapperScan(basePackages = ["x.spring.hello.repository"])
class MybatisApplicationfun main(args: Array<String>) {runApplication<MybatisApplication>(*args)
}
MyBatis++ Beans
package x.spring.hello.modelimport com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableIdclass User {@TableId(type = IdType.ASSIGN_UUID)var id = ""var name = ""var age = 0
}
package x.spring.hello.modelclass UserExample {var id: String? = nullvar name: String? = nullvar age: Int? = null
}
package x.spring.hello.modelclass UserRoleQueryResult {var name = ""var role = ""
}
MyBatis++ Mapper

mapper sometimes called interface, service or repository in other projects

package x.spring.hello.repositoryimport link.thingscloud.quick.mybatisplus.base.BaseMapper
import org.apache.ibatis.annotations.Select
import x.spring.hello.model.User
import x.spring.hello.model.UserRoleQueryResultinterface 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 roleon 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.mybatisimport com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberPropertiesfun 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.memberPropertiesproperties.forEach { propertyS ->val value = propertyS.get(example)value.takeIf { it != null } ?: return@forEachval property = T::class.findPropertyByName(propertyS.name)property.takeIf { it != null } ?: return@forEachwrapper.set(property, value)}}return QueryCondition(configurator)
}inline fun <reified T : Any> KClass<T>.findPropertyByName(name: String): KProperty1<T, *>? {return memberProperties.firstOrNull { it.name == name }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/12913.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

deepseek、qwen等多种模型本地化部署

想要在本地部署deepseek、qwen等模型其实很简单,快跟着小编一起部署吧 1 环境搭建 1.1下载安装环境 首先我们需要搭建一个环境ollama,下载地址如下 :Ollama 点击Download 根据自己电脑的系统选择对应版本下载即可 1.2 安装环境(window为例) 可以直接点击安装包进行安…

穷举vs暴搜vs深搜vs回溯vs剪枝系列一>黄金矿工

目录 决策树&#xff1a;代码设计代码&#xff1a; 决策树&#xff1a; 代码设计 代码&#xff1a; class Solution {boolean[][] vis;int ret,m,n;public int getMaximumGold(int[][] grid) {m grid.length;n grid[0].length;vis new boolean[m][n]; for(int i 0; i <…

基于springboot河南省旅游管理系统

基于Spring Boot的河南省旅游管理系统是一种专为河南省旅游行业设计的信息管理系统&#xff0c;旨在整合和管理河南省的旅游资源信息&#xff0c;为游客提供准确、全面的旅游攻略和服务。以下是对该系统的详细介绍&#xff1a; 一、系统背景与意义 河南省作为中国的中部省份&…

并发编程 - 线程同步(三)之原子操作Interlocked简介

上一章我们了解了3种处理多线程中共享资源安全的方法&#xff0c;今天我们将更近一步&#xff0c;学习一种针对简单线程同步场景的解决方案——Interlocked。 在此之前我们先学习一个概念——原子操作。 01、原子操作 原子操作&#xff0c;其概念源于化学领域&#xff0c;原子…

0205算法:最长连续序列、三数之和、排序链表

力扣128&#xff1a;最长连续序列 给定一个未排序的整数数组 nums &#xff0c;找出数字连续的最长序列&#xff08;不要求序列元素在原数组中连续&#xff09;的长度。 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 class Solution {public int longestConsecutive(in…

JAVA_内部类

定义&#xff1a;在类的内部再定义一个类 特点&#xff1a;内部类可以直接访问外部类中的成员变量&#xff0c;即使是私有的。 外部类要想访问内部类中的成员变量&#xff0c;必须先创建内部类对象。 什么时候使用内部类&#xff1a;B类是A类的一部分&#xff0c;且B单独存在没…

2024 JAVA面试题

第一章-Java基础篇 1、你是怎样理解OOP面向对象 面向对象是利于语言对现实事物进行抽象。面向对象具有以下特征&#xff1a; 继承****&#xff1a;****继承是从已有类得到继承信息创建新类的过程 封装&#xff1a;封装是把数据和操作数据的方法绑定起来&#xff0c;对数据的…

视频融合平台EasyCVR无人机场景视频压缩及录像方案

安防监控视频汇聚EasyCVR平台在无人机场景中发挥着重要的作用&#xff0c;通过高效整合视频流接入、处理与分发等功能&#xff0c;为无人机视频数据的实时监控、存储与分析提供了全面支持&#xff0c;广泛应用于安防监控、应急救援、电力巡检、交通管理等领域。 EasyCVR支持GB…

2025最新软件测试面试大全

前面看到了一些面试题&#xff0c;总感觉会用得到&#xff0c;但是看一遍又记不住&#xff0c;所以我把面试题都整合在一起&#xff0c;都是来自各路大佬的分享&#xff0c;为了方便以后自己需要的时候刷一刷&#xff0c;不用再到处找题&#xff0c;今天把自己整理的这些面试题…

Hugging Face GGUF 模型可视化

Hugging Face GGUF 模型可视化 1. Finding GGUF files (检索 GGUF 模型)2. Viewer for metadata & tensors info (可视化 GGUF 模型)References 无知小儿&#xff0c;仙家雄霸天下&#xff0c;依附强者才是唯一的出路。否则天地虽大&#xff0c;也让你们无路可走&#xff0…

【C++】多态详细讲解

本篇来聊聊C面向对象的第三大特性-多态。 1.多态的概念 多态通俗来说就是多种形态。多态分为编译时多态(静态多态)和运⾏时多态(动态多态)。 编译时多态&#xff1a;主要就是我们前⾯讲的函数重载和函数模板&#xff0c;他们传不同类型的参数就可以调⽤不同的函数&#xff0c;通…

oracle 基础语法复习记录

Oracle SQL基础 学习范围 学习SQL基础语法 掌握SELECT、INSERT、UPDATE、DELETE等基本操作。 熟悉WHERE、GROUP BY、ORDER BY、HAVING等子句。 理解表连接&#xff1a; 学习INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL OUTER JOIN等连接方式。 掌握聚合函数&#xff1a; 熟悉…

配置@别名路径,把@/ 解析为 src/

路径解析配置 webpack 安装 craco npm i -D craco/craco 项目根目录下创建文件 craco.config.js &#xff0c;内容如下 const path require(path) module.exports {webpack: {// 配置别名alias: {// 约定&#xff1a; 使用 表示src文件所在路径: path.resolve(__dirname,src)…

Vue前端开发-pinia之Actions插件

Store中的Actions部分&#xff0c;用于定义操作属性的方法&#xff0c;类似于组件中的methods部分&#xff0c;它与Getters都可以操作State属性&#xff0c;但在定义方法时&#xff0c;Getters是对State属性进行加工处理&#xff0c;再返回使用&#xff0c;属于内部计算;Action…

Java NIO详解

一、NIO简介 NIO 中的 N 可以理解为 Non-blocking&#xff0c;不单纯是 New&#xff0c;是解决高并发、I/O高性能的有效方式。 Java NIO 是Java1.4之后推出来的一套IO接口&#xff0c;NIO提供了一种完全不同的操作方式&#xff0c; NIO支持面向缓冲区的、基于通道的IO操作。 …

Java进阶笔记(中级)

-----接Java进阶笔记&#xff08;初级&#xff09;----- 目录 集合多线程 集合 ArrayList 可以通过List来接收ArrayList对象&#xff08;因为ArrayList实现了List接口&#xff09; 方法&#xff1a;接口名 柄名 new 实现了接口的类(); PS: List list new ArrayList();遍历…

21.2.2 保存

版权声明&#xff1a;本文为博主原创文章&#xff0c;转载请在显著位置标明本文出处以及作者网名&#xff0c;未经作者允许不得用于商业目的。 如果打开某个Excel文件修改后&#xff0c;需要保存到原文件或者用新的文件名保存&#xff0c;在 Excel.Application.Quit() 前使用W…

基于微信小程序的校园水电费管理平台设计与实现

目录 摘要 系统展示 技术介绍 MySQL数据库 Vue框架 代码实现 管理员实现登录后端代码 连接数据库 前端代码实现 获取源码 摘要 随着社会的发展&#xff0c;社会的方方面面都在利用信息化时代的优势。互联网的优势和普及使得各种系统的开发成为必需。 本文以实际运用…

基于springboot的体质测试数据分析及可视化设计

作者&#xff1a;学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等 文末获取“源码数据库万字文档PPT”&#xff0c;支持远程部署调试、运行安装。 项目包含&#xff1a; 完整源码数据库功能演示视频万字文档PPT 项目编码&#xff1…

离散时间傅里叶变换(DTFT)公式详解:周期性与连续性剖析

摘要 离散时间傅里叶变换&#xff08;DTFT&#xff09;是数字信号处理领域的重要工具&#xff0c;它能将离散时间信号从时域转换到频域&#xff0c;揭示信号的频率特性。本文将深入解读DTFT公式&#xff0c;详细阐述其具有周期性和连续性的原因&#xff0c;帮助读者全面理解DT…