Singerw's Repository Singerw's Repository
首页
  • 相关文章

    • HTML相关文章
    • CSS相关文章
    • JavaScript相关文章
  • 学习笔记

    • JavaScript笔记
    • ES6笔记
    • Vue笔记
  • 相关文章

    • Spring相关文章
    • SpringBoot相关文章
    • MyBatis相关文章
    • MySQL相关文章
  • 学习笔记

    • SpringBoot笔记
    • Spring笔记
    • MyBatis笔记
    • MySQL笔记
    • JavaWeb笔记
    • JavaCore笔记
  • 学习笔记

    • Linux笔记
    • Git笔记
    • 技术文档
  • 偏门技术

    • GitHub技巧
    • 博客搭建
    • 科学上网
  • 安装教程

    • JDK
    • MySQL
    • Node.js
    • Linux
  • 终身学习
  • 面试人生
  • 心情杂货
  • 生活随笔
  • 归档
  • 标签
GitHub (opens new window)

Singerw

谁能够凭爱意将富士山私有
首页
  • 相关文章

    • HTML相关文章
    • CSS相关文章
    • JavaScript相关文章
  • 学习笔记

    • JavaScript笔记
    • ES6笔记
    • Vue笔记
  • 相关文章

    • Spring相关文章
    • SpringBoot相关文章
    • MyBatis相关文章
    • MySQL相关文章
  • 学习笔记

    • SpringBoot笔记
    • Spring笔记
    • MyBatis笔记
    • MySQL笔记
    • JavaWeb笔记
    • JavaCore笔记
  • 学习笔记

    • Linux笔记
    • Git笔记
    • 技术文档
  • 偏门技术

    • GitHub技巧
    • 博客搭建
    • 科学上网
  • 安装教程

    • JDK
    • MySQL
    • Node.js
    • Linux
  • 终身学习
  • 面试人生
  • 心情杂货
  • 生活随笔
  • 归档
  • 标签
GitHub (opens new window)
  • MyBatis学习笔记

  • MyBatis-Plus学习笔记

    • 《MyBatis-Plus》学习笔记
      • 1、ID_WORKER
      • 2、主键自增
      • 其与类型的源码解释
      • 方式一:数据库级别
      • 方式二:代码级别
      • 步骤一、导入插件
      • 步骤二、测试使用!
    • MyBatis-Plus—配置日志
    • MyBatis-Plus—主键生成策略
    • MyBatis-Plus—日期时间自动填充
    • MyBatis-Plus—性能分析插件
    • MyBatis-Plus—条件构造器(wrapper)
    • MyBatis-Plus—代码自动生成器
  • 《MyBatis》学习笔记
  • MyBatis-Plus学习笔记
Singerw
2021-10-07

《MyBatis-Plus》学习笔记

# MyBatis-Plus学习笔记

# 一、MyBatis-Plus—配置日志

我们所有的sql是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!

# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
1
2

配置完毕日志之后,后面的学习就需要注意这个自动生成的SQL,你们就会喜欢上 MyBatis-Plus!

# 二、MyBatis-Plus—主键生成策略

MyBatis-Plus 数据库插入时的id的默认值为:全局的唯一id

# 1、ID_WORKER

默认 ID_WORKER 全局唯一id

分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为 毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味 着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯 一!

# 2、主键自增

我们需要配置主键自增:

  • 实体类字段上 @TableId(type = IdType.AUTO)
  • 数据库字段一定要是自增!

再次测试插入即可!这时主键就是自增的状态。

# 其与类型的源码解释

public enum IdType {
    AUTO(0), // 数据库id自增
    NONE(1), // 未设置主键
    INPUT(2), // 手动输入
    ID_WORKER(3), // 默认的全局唯一id
    UUID(4), // 全局唯一id uuid
    ID_WORKER_STR(5); //ID_WORKER 字符串表示法
}
1
2
3
4
5
6
7
8

# 三、MyBatis-Plus—日期时间自动填充

创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新! 阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需 要自动化!

# 方式一:数据库级别

数据库级别(但是在工作中不允许你修改数据库,不推荐这种!)

步骤一、在表中新增字段 create_time,update_time

步骤二、实体类同步,插入新的属性!

private Date createTime;
private Date updateTime;
1
2

步骤三、测试,更新查看结果即可

# 方式二:代码级别

代码级别,推荐使用!

步骤一:删除数据库的时间字段的默认值、更新操作!

步骤二:实体类时间字段属性上需要增加注解!

// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
1
2
3
4
5
6

步骤三:编写处理器来处理这个注解即可!

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {
    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill.....");
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject
        metaObject
            this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill.....");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

步骤四:测试插入,测试更新、观察时间即可!

# 四、MyBatis-Plus—性能分析插件

我们在平时的开发中,会遇到一些慢sql。测试! druid,,,,, 作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间 MP也提供性能分析插件,如果超过这个时间就停止运行!

# 步骤一、导入插件

/**
* SQL执行效率插件
*/
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor() {
    PerformanceInterceptor performanceInterceptor = new
        PerformanceInterceptor();
    performanceInterceptor.setMaxTime(100); // ms设置sql执行的最大时间,如果超过了则不
    执行
        performanceInterceptor.setFormat(true); // 是否格式化代码
    return performanceInterceptor;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

记住,要在SpringBoot中配置环境为dev或者 test 环境才有效!

# 步骤二、测试使用!

@Test
void contextLoads() {
    // 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
    // 查询全部用户
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
}
1
2
3
4
5
6
7

使用性能分析插件,可以帮助我们提高效率!

# 五、MyBatis-Plus—条件构造器(wrapper)

十分重要:Wrapper 我们写一些复杂的sql就可以使用它来替代!

MyBatis-Plus文档:https://baomidou.com/guide/wrapper.html

# 六、MyBatis-Plus—代码自动生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、 Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;

// 代码自动生成器
public class KuangCode {
    public static void main(String[] args) {
        // 需要构建一个 代码自动生成器 对象
        AutoGenerator mpg = new AutoGenerator();
        // 配置策略
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath+"/src/main/java");
        gc.setAuthor("狂神说");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去Service的I前缀
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        //2、设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community?
                   useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
                   dsc.setDriverName("com.mysql.cj.jdbc.Driver");
                   dsc.setUsername("root");
                   dsc.setPassword("123456");
                   dsc.setDbType(DbType.MYSQL);
                   mpg.setDataSource(dsc);
                   //3、包的配置
                   PackageConfig pc = new PackageConfig();
                   pc.setModuleName("blog");
                   pc.setParent("com.kuang");
                   pc.setEntity("entity");
                   pc.setMapper("mapper");
                   pc.setService("service");
                   pc.setController("controller");
                   mpg.setPackageInfo(pc);
                   //4、策略配置
                   StrategyConfig strategy = new StrategyConfig();
                   strategy.setInclude("blog_tags","course","links","sys_settings","user_record","
                                       user_say"); // 设置要映射的表名
                                       strategy.setNaming(NamingStrategy.underline_to_camel);
                                       strategy.setColumnNaming(NamingStrategy.underline_to_camel);
                                       strategy.setEntityLombokModel(true); // 自动lombok;
                                       strategy.setLogicDeleteFieldName("deleted");
                                       // 自动填充配置
                                       TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
                                       TableFill gmtModified = new TableFill("gmt_modified",
                                                                             FieldFill.INSERT_UPDATE);
                                       ArrayList<TableFill> tableFills = new ArrayList<>();
                                       tableFills.add(gmtCreate);
                                       tableFills.add(gmtModified);
                                       strategy.setTableFillList(tableFills);
                                       // 乐观锁
                                       strategy.setVersionFieldName("version");
                                       strategy.setRestControllerStyle(true);
                                       strategy.setControllerMappingHyphenStyle(true); //
                                       localhost:8080/hello_id_2
                                       mpg.setStrategy(strategy);
                                       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

企业级别

package com.onesports.office.material.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.BeetlTemplateEngine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * mybatisplus代码生成器
 *
 * @author yangaj
 **/
@Component
public class MybatisplusGenerator {

    @Value("${spring.datasource.url}")
    private String dataSourceUrl;
    @Value("${spring.datasource.driver-class-name}")
    private String dataSourceDriver;
    @Value("${spring.datasource.username}")
    private String dataSourceUsername;
    @Value("${spring.datasource.password}")
    private String dataSourcePwd;
    @Value("${mybatis-plus.global-config.author}")
    private String author;
    @Value("${mybatis-plus.global-config.module}")
    private String module;
    @Value("${mybatis-plus.package-config.biz-module}")
    private String bizModuleName;
    @Value("${mybatis-plus.package-config.parent-path}")
    private String parentPath;
    @Value("${mybatis-plus.strategy-config.table-name}")
    private String tableName;
    @Value("${mybatis-plus.strategy-config.super-entity-class}")
    private String superEntityClass;

    public void generate() {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        String outputDir = projectPath.replaceAll("office-material-generator", module);
        //根据需求开关   数据库json属性转换自定义sql需要引用
        gc.setBaseResultMap(true);
        gc.setOutputDir(outputDir + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setServiceImplName("%sService");
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dataSourceUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName(dataSourceDriver);
        dsc.setUsername(dataSourceUsername);
        dsc.setPassword(dataSourcePwd);
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("");
        pc.setParent(parentPath);
        pc.setEntity("beans.entity.".concat(bizModuleName));
        pc.setMapper("mapper.".concat(bizModuleName));
        pc.setController("");
        pc.setService("");
        pc.setServiceImpl("service.".concat(bizModuleName));
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        //模板引擎beetl
        String templatePath = "/templates/mapper.xml.btl";
        // 如果模板引擎是 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() + "/"
                // 修改成要生成的业务模块名 如: base,sys,shedule

                return outputDir + "/src/main/resources/mapper/" + bizModuleName + "/"
                    + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        //        templateConfig.setEntity("templates/entity.java");
        templateConfig.setService("");
        templateConfig.setServiceImpl("templates/manager.java");
        templateConfig.setController("");

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(superEntityClass);
        strategy.setEntityLombokModel(true);
        strategy.setChainModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setTablePrefix("1tmm_");
        //        strategy.setFieldPrefix("1tpm_");
        //        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        // 公共父类 你自己的父类控制器,没有就不用设置!
        //        strategy.setSuperControllerClass("");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id", "create_by", "create_time", "modified_by", "modified_time", "count", "is_delete");
        strategy.setInclude(tableName.split(","));
        strategy.setControllerMappingHyphenStyle(true);
        //        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new BeetlTemplateEngine());
        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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
编辑 (opens new window)
#MyBatis-Plus
generator插件自动生成代码
MyBatis-Plus—配置日志

← generator插件自动生成代码 MyBatis-Plus—配置日志→

最近更新
01
Maven资源导出问题终极版
10-12
02
MyBatis-Plus—配置日志
10-07
03
MyBatis-Plus—主键生成策略
10-07
更多文章>
Theme by Vdoing | Copyright © 2020-2021 版权所有 | repository.singerw.com
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×