当前位置:   article > 正文

mybatis-plus学习笔记(Kotlin)_mybatisplus kotlin

mybatisplus kotlin

mybatis-plus学习笔记

前言

项目基于Springboot + kotlin

1、数据库

auth表

字段名类型说明
idint主键且自增
authvarchar
auth_namevarchar

user表

字段名类型说明
userint主键
passvarchar
usernamevarchar
authint
creat_timedatetime

关联

其中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>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3、代码生成器

一定要在springboot启动类上配置@MapperScan注解!!!

一定要在springboot启动类上配置@MapperScan注解!!!

一定要在springboot启动类上配置@MapperScan注解!!!

@MapperScan("com.jiayou.bus")  //扫描mapper
@SpringBootApplication
open class MybatisPlusApplication
fun main(args: Array<String>) {
    runApplication<MybatisPlusApplication>(*args)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
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();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122

代码生成完成后:

会在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               #实体类型别名
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

mapper

interface AuthMapper : BaseMapper<Auth?>
  • 1

业务类

interface IAuthService : IService<Auth?>

//@Service注解的业务类需要被mybatis-plus代理,所以在kotlin应设置为open(可继承)
@Service
open class AuthServiceImpl : ServiceImpl<AuthMapper?, Auth?>(), IAuthService  
  • 1
  • 2
  • 3
  • 4
  • 5

单元测试

@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)
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

输出

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
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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, nullnull)

    companion object {
        private const val serialVersionUID = 1L
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

mapper接口

interface UserMapper : BaseMapper<User?> {
    fun selectAllAssociation(): List<User?>?
}
  • 1
  • 2
  • 3

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

测试

@SpringBootTest
class MybatisPlusApplicationTests {


    @Autowired
    private lateinit var authServiceImpl: AuthServiceImpl

    @Autowired
    private lateinit var userServiceImpl: UserServiceImpl

    @Test
    fun myTest() {
        userServiceImpl.baseMapper.selectAllAssociation()?.forEach { println(it) }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

一对多

实体类

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
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

mapper接口

interface AuthMapper : BaseMapper<Auth?> {
    fun selectAllRelation(): List<Auth?>?
}
  • 1
  • 2
  • 3

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

测试

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    private lateinit var authServiceImpl: AuthServiceImpl

    @Test
    fun myTest() {
        authServiceImpl.baseMapper?.selectAllRelation()?.forEach(System.out::println)
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/1009453
推荐阅读
相关标签
  

闽ICP备14008679号