mybatis-plus学习笔记
前言
项目基于Springboot + kotlin。
1、数据库
auth表
字段名 | 类型 | 说明 |
---|---|---|
id | int | 主键且自增 |
auth | varchar | |
auth_name | varchar |
user表
字段名 | 类型 | 说明 |
---|---|---|
user | int | 主键 |
pass | varchar | |
username | varchar | |
auth | int | |
creat_time | datetime |
关联
其中user表的auth字段与auth表的id对应。
2、Maven
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--mybatis-plus代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!--mybatis-plus代码生成器模板引擎-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
3、代码生成器
一定要在springboot启动类上配置@MapperScan注解!!!
一定要在springboot启动类上配置@MapperScan注解!!!
一定要在springboot启动类上配置@MapperScan注解!!!
@MapperScan("com.jiayou.bus") //扫描mapper
@SpringBootApplication
open class MybatisPlusApplication
fun main(args: Array<String>) {
runApplication<MybatisPlusApplication>(*args)
}
package com.jiayou;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置(一定要配置好模板的生成路径!!!)
// 全局配置(一定要配置好模板的生成路径!!!)
// 全局配置(一定要配置好模板的生成路径!!!)
// 全局配置(一定要配置好模板的生成路径!!!)
// 全局配置(一定要配置好模板的生成路径!!!)
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir") + "/mybatis-plus";
gc.setOutputDir(projectPath + "/src/main/kotlin");
gc.setAuthor("lishuang");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/syxy_bus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.jiayou"); //配置包名
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setSuperEntityClass(Model.class);
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
代码生成完成后:
会在src目录下生成包和对应的entity,mapper,service,controller。(在kotlin中是在kotlin目录下)
会在资源路径下(resources目录)生成mapper映射文件
4、Yaml配置
spring:
application:
name: mybatis-plus
datasource:
url: jdbc:mysql://localhost:3306/syxy_bus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
#扫描mapper路径
mybatis-plus:
mapper-locations: classpath:mapper/kantu/*.xml
configuration: #配置日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志实现类
map-underscore-to-camel-case: true #驼峰转换
type-aliases-package: com.jiayou.bus.entity #实体类型别名
5、测试
实体类
Auth.kt
@TableName("auth")
data class Auth(
@TableId("id", type = IdType.AUTO)
var id: Int? = null,
@TableField("auth")
var auth: String? = null,
@TableField("authName")
var authName: String? = null) : Model<Auth>() {
companion object {
private const val serialVersionUID = 1L
}
}
mapper
interface AuthMapper : BaseMapper<Auth?>
业务类
interface IAuthService : IService<Auth?>
//@Service注解的业务类需要被mybatis-plus代理,所以在kotlin应设置为open(可继承)
@Service
open class AuthServiceImpl : ServiceImpl<AuthMapper?, Auth?>(), IAuthService
单元测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private lateinit var authServiceImpl: AuthServiceImpl
@Test
fun myTest() {
authServiceImpl.list().forEach { println(it) }
authServiceImpl.baseMapper?.selectList(QueryWrapper<Auth>())?.forEach(System.out::println)
}
}
输出
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@bc09d57] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@2131366717 wrapping com.mysql.cj.jdbc.ConnectionImpl@241fbec] will not be managed by Spring
Original SQL: SELECT id,auth,auth_name FROM auth
parser sql: SELECT id, auth, auth_name FROM auth
==> Preparing: SELECT id, auth, auth_name FROM auth
==> Parameters:
<== Columns: id, auth, auth_name
<== Row: 1, admin, 超级管理员
<== Row: 2, user, 普通用户
<== Row: 3, super1, 超管1
<== Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@bc09d57]
Auth(id=1, auth=admin, authName=超级管理员)
Auth(id=2, auth=user, authName=普通用户)
Auth(id=3, auth=super1, authName=超管1)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@9fe720a] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@345142475 wrapping com.mysql.cj.jdbc.ConnectionImpl@241fbec] will not be managed by Spring
Original SQL: SELECT id,auth,auth_name FROM auth
parser sql: SELECT id, auth, auth_name FROM auth
==> Preparing: SELECT id, auth, auth_name FROM auth
==> Parameters:
<== Columns: id, auth, auth_name
<== Row: 1, admin, 超级管理员
<== Row: 2, user, 普通用户
<== Row: 3, super1, 超管1
<== Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@9fe720a]
Auth(id=1, auth=admin, authName=超级管理员)
Auth(id=2, auth=user, authName=普通用户)
Auth(id=3, auth=super1, authName=超管1)
6、映射关系
一对一
实体类
Auth.kt(一)
@TableName("auth")
data class Auth(
@TableId("id", type = IdType.AUTO)
var id: Int? = null,
@TableField("auth")
var auth: String? = null,
@TableField("auth_name")
var authName: String? = null,
@TableField(exist = false) //声明该字段不是数据库表字段
var user: List<User?>? = null) : Model<Auth>(), java.io.Serializable {
constructor() : this(null, null, null, null)
companion object {
private const val serialVersionUID = 1L
}
}
User.kt(一)
@TableName("user")
data class User(
@TableId("user")
var user: String? = null,
@TableField("pass")
var pass: String? = null,
@TableField("username")
var username: String? = null,
@TableField("auth")
var auth: Int? = null,
@TableField("creat_time")
var creatTime: LocalDateTime? = null,
@TableField(exist = false)
var _auth: Auth? = null
) : Model<User>(), java.io.Serializable {
constructor() : this(null, null, null, null, null,null)
companion object {
private const val serialVersionUID = 1L
}
}
mapper接口
interface UserMapper : BaseMapper<User?> {
fun selectAllAssociation(): List<User?>?
}
mapper映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiayou.bus.mapper.UserMapper">
<select id="selectAllAssociation" resultMap="myMap">
select *
from syxy_bus.user
</select>
<resultMap id="myMap" type="com.jiayou.bus.entity.User" autoMapping="true">
<id property="user" column="user"/>
<result property="auth" column="auth"/>
<association property="_auth" column="auth" select="selectAuth">
</association>
</resultMap>
<select id="selectAuth" resultType="com.jiayou.bus.entity.Auth">
select *
from syxy_bus.auth
where id = #{auth}
</select>
</mapper>
测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private lateinit var authServiceImpl: AuthServiceImpl
@Autowired
private lateinit var userServiceImpl: UserServiceImpl
@Test
fun myTest() {
userServiceImpl.baseMapper.selectAllAssociation()?.forEach { println(it) }
}
}
一对多
实体类
Auth.kt(一)
@TableName("auth")
data class Auth(
@TableId("id", type = IdType.AUTO)
var id: Int? = null,
@TableField("auth")
var auth: String? = null,
@TableField("auth_name")
var authName: String? = null,
@TableField(exist = false) //声明该字段不是数据库表字段
var user: List<User?>? = null) : Model<Auth>(), java.io.Serializable {
constructor() : this(null, null, null, null)
companion object {
private const val serialVersionUID = 1L
}
}
User.kt(多)
@TableName("user")
data class User(
@TableId("user")
var user: String? = null,
@TableField("pass")
var pass: String? = null,
@TableField("username")
var username: String? = null,
@TableField("auth")
var auth: Int? = null,
@TableField("creat_time")
var creatTime: LocalDateTime? = null) : Model<User>(),java.io.Serializable {
constructor() : this(null, null, null, null, null)
companion object {
private const val serialVersionUID = 1L
}
}
mapper接口
interface AuthMapper : BaseMapper<Auth?> {
fun selectAllRelation(): List<Auth?>?
}
mapper映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiayou.bus.mapper.AuthMapper">
<select id="selectAllRelation" resultMap="myMap">
select *
from syxy_bus.auth
</select>
<resultMap id="myMap" type="com.jiayou.bus.entity.Auth" >
<id column="id" property="id"/>
<collection property="user" column="id" ofType="com.jiayou.bus.entity.User" select="selectUser">
</collection>
</resultMap>
<select id="selectUser" resultType="com.jiayou.bus.entity.User">
select *
from syxy_bus.user
where user.auth = #{sda};
<!--只传入了一个参数,该参数可以任意命名,符合标识符即可。-->
</select>
</mapper>
测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private lateinit var authServiceImpl: AuthServiceImpl
@Test
fun myTest() {
authServiceImpl.baseMapper?.selectAllRelation()?.forEach(System.out::println)
}
}