• MyBatis-Plus使用


    目录

    1.springboot整合定时器

    1.1 何为定时器

    1.2 为什么使用定时器

    1.3 如何来使用定时器

     2.mp

    2.1 何为mp

    2.2 mp特点

    2.3 如何使用

    3.mp对应的方法

    3.1 mp-增加

    3.2 mp-删除

    3.3 mp-查询

    3.3.1 根据各种条件查询

    3.3.2 根据条件查询一条记录

    3.3.3 分页查询

    3.3.4 联表查询也使用mp的分页

    4.mp的代码生成器(旧)

    4.1 依赖

    4.2 测试代码

    5.举个例子

    5.1 依赖

    5.2 自动生成测试类

    5.3 启动类

    5.4 配置类

    5.4.1 MybatisPlusConfig

    5.4.2 MyMetaObjectHandler

    5.5 controller层(自动生成)

    5.6 entity层(自动生成,部分进行修改)

    5.6.1 TblDept

    5.6.2 User

    5.7 Mapper层(自动生成)

    5.8 service层(自动生成)

    5.9 mapper层

    5.10 Mapper层(自动生成)

    5.11 application.properties配置


    1.springboot整合定时器

    1.1 何为定时器

    在指定的时间,执行相应的业务代码。

    1.2 为什么使用定时器

    比如: OSS文件系统服务器,会产生大量冗余文件。定时删除冗余文件【凌晨2~3点】。

    比如: 下单后半个未支付--取消订单。

    1.3 如何来使用定时器

    (1)引入定时器依赖。

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-quartzartifactId>
    4. dependency>

    (2)编写定义任务代码。

    1. @Component//交给Spring管理
    2. public class Scheduling {
    3. //直接运行,任务代码cron:定义定时任务的规则 https://www.pppet.net/
    4. @Scheduled(cron = "0/1 * * * * ? ")
    5. public void test01(){
    6. System.out.println("啦啦啦啦");
    7. }
    8. }

     cron = "0/1 * * * * ? "生成的方式是使用下述链接

    在线Cron表达式生成器Cron表达式在线生成器,方便的在线生成各类Cron表达式,并可以将Cron表达式的可视化双向解析和生成.https://www.pppet.net/(3) 开启定时任务的注解

     2.mp

    2.1 何为mp

    MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。单表操作的都不需要自己在写sql语句。

    2.2 mp特点

    • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

    • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

    • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现-==单表大部分 CRUD 操作==,更有强大的==条件构造器[条件封装成一个条件类]==,满足各类使用需求

    • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

    • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

    • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

    • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

    • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

    • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询。

    • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库.

    • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

    • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作.

    2.3 如何使用

    快速开始 | MyBatis-Plus
    (1)创建数据库和表

    1. DROP TABLE IF EXISTS user;
    2. CREATE TABLE user
    3. (
    4. id BIGINT(20) NOT NULL COMMENT '主键ID',
    5. name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    6. age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    7. email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    8. PRIMARY KEY (id)
    9. );
    10. DELETE FROM user;
    11. INSERT INTO user (id, name, age, email) VALUES
    12. (1, 'Jone', 18, 'test1@baomidou.com'),
    13. (2, 'Jack', 20, 'test2@baomidou.com'),
    14. (3, 'Tom', 28, 'test3@baomidou.com'),
    15. (4, 'Sandy', 21, 'test4@baomidou.com'),

    (2)依赖

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-boot-starterartifactId>
    4. <version>3.5.1version>
    5. dependency>

    (3)创建实体类

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. //若表名不一致@TableName(value = "")
    5. public class User {
    6. @TableId(value = "id",type = IdType.AUTO)
    7. private Integer id;
    8. //如果属性和列名不一致 @TableField(value = )
    9. private String name;
    10. private Integer age;
    11. private String email;
    12. @TableField(fill = FieldFill.INSERT)
    13. private LocalDateTime gmtCreated;
    14. @TableField(fill = FieldFill.UPDATE)
    15. private LocalDateTime gmtUpdated;
    16. @TableLogic//逻辑列
    17. private Integer isdeleted;
    18. @TableField(exist = false)
    19. private Dept dept;
    20. }

    (4)dao

    1. //BaseMapper提供了单表的所有操作 crud
    2. @Mapper
    3. public interface UserMapper extends BaseMapper {
    4. IPage selectUserWithDept(IPage page, @Param("ew") Wrapper wrapper);
    5. }

    (5)测试

    1. @Autowired
    2. private UserMapper userMapper;
    3. @Test
    4. void contextLoads() {
    5. User user = userMapper.selectById(1);
    6. System.out.println(user);
    7. }

    3.mp对应的方法

    3.1 mp-增加

    注意要在实体类对应的type编写:
            主键mp提供相应的生成策略
             AUTO,递增策略,如果使用该策略必须要求数据表的列也是递增。
             NONE,没有策略,必须人为的输入id值,若不输入则会产生负数
             INPUT,没有策略,必须人为的输入id值
             ASSIGN_ID,随机生成一个Long类型的值。该值一定是唯一。而且每次生成都不会相同。算法:雪花算法。 适合分布式主键。
             ASSIGN_UUID,随机产生一个String类型的值。该值也是唯一的。

    1. /**
    2. * 主键mp提供相应的生成策略:
    3. * AUTO(0),递增策略,如果使用该策略必须要求数据表的列也是递增。
    4. * NONE(1),没有策略,必须人为的输入id值,若不输入则会产生负数
    5. * INPUT(2),没有策略,必须人为的输入id值
    6. * ASSIGN_ID(3), 随机生成一个Long类型的值。该值一定是唯一。而且每次生成都不会相同。算法:雪花算法。 适合分布式主键。
    7. * ASSIGN_UUID(4); 随机产生一个String类型的值。该值也是唯一的。
    8. */
    9. @Test
    10. public void insert(){
    11. User user=new User();
    12. user.setName("小樱");
    13. user.setEmail("test4@1232243");
    14. user.setAge(17);
    15. System.out.println("添加前=============="+user);
    16. int insert = userMapper.insert(user);//mp会把生成的主键值复制给对象??
    17. System.out.println("添加后=============="+user);
    18. System.out.println(insert);
    19. }

    3.2 mp-删除

    1. /**
    2. * 实际开发中: 我们的删除可能是逻辑删除。所谓的逻辑删除就是修改功能。把某个列修改以删除的状态值。
    3. * 只对自动注入的 sql 起效:
    4. * 插入: 不作限制---
    5. * 查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
    6. * 更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
    7. * 删除: 转变为 更新
    8. * (1)增加一个逻辑字段: isdeleted 0表示未删除 1表示删除.
    9. * (2)实体类上的字段添加 @TableLogic.
    10. */
    11. @Test
    12. public void testDelete(){
    13. int i = userMapper.deleteById(6);
    14. //根据主键删除
    15. System.out.println(i);
    16. }

    3.3 mp-查询

    3.3.1 根据各种条件查询

    1. @Test
    2. public void testSelectByCondition(){
    3. //Wrapper:封装了关于查询的各种条件方法。有三个子类最常用: QueryWrapper查询条件 UpdateWrapper修改条件 LambdaQueryWrapper查询使用lambda表达式条件
    4. QueryWrapper wrapper=new QueryWrapper<>();
    5. wrapper.between("age",15,28);//年龄的要查找的范围值
    6. wrapper.select("name","age");//选择select *的*中要查询的内容
    7. wrapper.like("name","a");//名字的模糊查询
    8. System.out.println(userMapper.selectList(wrapper));//要同时满足以上三个条件,才可以输出
    9. }

    3.3.2 根据条件查询一条记录

    1. @Test
    2. public void testSelectOne(){
    3. QueryWrapper wrapper=new QueryWrapper<>();
    4. wrapper.eq("username","");
    5. wrapper.eq("password","");
    6. User user = userMapper.selectOne(wrapper);
    7. }

    3.3.3 分页查询

    1. /**
    2. * (1)添加分页拦截器
    3. * (2)调用分页方法
    4. */
    5. @Test
    6. public void testPage(){
    7. //P page, 分页对象 Page
    8. // @Param("ew") Wrapper queryWrapper
    9. Page page=new Page<>(1,3);
    10. userMapper.selectPage(page,null);//把查询的结果自动封装到Page对象中
    11. System.out.println("总页码"+page.getPages());
    12. System.out.println("总条数"+page.getTotal());
    13. System.out.println("当前页记录"+page.getRecords());
    14. }

    3.3.4 联表查询也使用mp的分页

    1. /**
    2. * 联表查询 使用mp的分页功能。
    3. */
    4. @Test
    5. public void testLianBiao(){
    6. //P page, 分页对象 Page
    7. // @Param("ew") Wrapper queryWrapper
    8. Page page=new Page<>(1,3);
    9. QueryWrapper wrapper=new QueryWrapper<>();
    10. wrapper.eq("name","小樱");
    11. IPage userIPage = userMapper.selectUserWithDept(page, wrapper);
    12. System.out.println("总页码"+page.getPages());
    13. System.out.println("总条数"+page.getTotal());
    14. System.out.println("当前页记录"+page.getRecords());
    15. }
    1. //BaseMapper提供了单表的所有操作 crud
    2. @Mapper
    3. public interface UserMapper extends BaseMapper {
    4. IPage selectUserWithDept(IPage page, @Param("ew") Wrapper wrapper);
    5. }
    1. <mapper namespace="com.qy151.dao.UserMapper">
    2. <resultMap id="baseMapper" type="com.qy151.entity.User" autoMapping="true">
    3. <id column="id" property="id"/>
    4. <association property="dept" javaType="com.qy151.entity.Dept" autoMapping="true">
    5. <id column="did" property="id"/>
    6. association>
    7. resultMap>
    8. <select id="selectUserWithDept" resultMap="baseMapper">
    9. select * from user u join tbl_dept d on u.did=d.did where isdeleted=0
    10. <if test="ew!=null">
    11. and ${ew.sqlSegment}
    12. if>
    13. select>
    14. mapper>

    4.mp的代码生成器(旧)

    4.1 依赖

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-generatorartifactId>
    4. <version>3.4.1version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.apache.velocitygroupId>
    8. <artifactId>velocity-engine-coreartifactId>
    9. <version>2.3version>
    10. dependency>
    11. <dependency>
    12. <groupId>org.freemarkergroupId>
    13. <artifactId>freemarkerartifactId>
    14. <version>2.3.30version>
    15. dependency>

    4.2 测试代码

    1. package com.qy151wd.autiomp;
    2. import com.baomidou.mybatisplus.core.toolkit.StringPool;
    3. import com.baomidou.mybatisplus.generator.AutoGenerator;
    4. import com.baomidou.mybatisplus.generator.InjectionConfig;
    5. import com.baomidou.mybatisplus.generator.config.*;
    6. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    7. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    8. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    9. import java.util.ArrayList;
    10. import java.util.List;
    11. // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
    12. public class CodeGenerator {
    13. /**
    14. *

    15. * 读取控制台内容
    16. *

    17. */
    18. public static void main(String[] args) {
    19. // 代码生成器
    20. AutoGenerator mpg = new AutoGenerator();
    21. // 全局配置
    22. GlobalConfig gc = new GlobalConfig();
    23. gc.setOutputDir("./src/main/java");
    24. gc.setAuthor("wd");
    25. gc.setOpen(false);
    26. gc.setSwagger2(true); //实体属性 Swagger2 注解
    27. mpg.setGlobalConfig(gc);
    28. // 数据源配置
    29. DataSourceConfig dsc = new DataSourceConfig();
    30. dsc.setUrl("jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai");
    31. // dsc.setSchemaName("public");
    32. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    33. dsc.setUsername("root");
    34. dsc.setPassword("123456");
    35. mpg.setDataSource(dsc);
    36. // 包配置
    37. PackageConfig pc = new PackageConfig();
    38. pc.setModuleName("autiomp");
    39. pc.setParent("com.qy151wd");
    40. mpg.setPackageInfo(pc);
    41. // 自定义配置
    42. InjectionConfig cfg = new InjectionConfig() {
    43. @Override
    44. public void initMap() {
    45. // to do nothing
    46. }
    47. };
    48. // 如果模板引擎是 freemarker
    49. String templatePath = "/templates/mapper.xml.ftl";
    50. // 如果模板引擎是 velocity
    51. // String templatePath = "/templates/mapper.xml.vm";
    52. // 自定义输出配置
    53. List focList = new ArrayList<>();
    54. // 自定义配置会被优先输出
    55. focList.add(new FileOutConfig(templatePath) {
    56. @Override
    57. public String outputFile(TableInfo tableInfo) {
    58. tableInfo.setName(tableInfo.getName().replace("tbl_",""));
    59. //tableInfo.setEntityName(tableInfo.getEntityName().replace("Tbl",""));
    60. tableInfo.setControllerName(tableInfo.getControllerName().replace("Tbl",""));
    61. tableInfo.setServiceName(tableInfo.getServiceName().replace("Tbl",""));
    62. tableInfo.setServiceImplName(tableInfo.getServiceImplName().replace("Tbl",""));
    63. tableInfo.setMapperName(tableInfo.getMapperName().replace("Tbl",""));
    64. tableInfo.setXmlName(tableInfo.getXmlName().replace("Tbl",""));
    65. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
    66. return "./src/main/resources/mapper/"
    67. + "/" + tableInfo.getEntityName().replace("Tbl","") + "Mapper" + StringPool.DOT_XML;
    68. }
    69. });
    70. /*
    71. cfg.setFileCreate(new IFileCreate() {
    72. @Override
    73. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
    74. // 判断自定义文件夹是否需要创建
    75. checkDir("调用默认方法创建的目录,自定义目录用");
    76. if (fileType == FileType.MAPPER) {
    77. // 已经生成 mapper 文件判断存在,不想重新生成返回 false
    78. return !new File(filePath).exists();
    79. }
    80. // 允许生成模板文件
    81. return true;
    82. }
    83. });
    84. */
    85. cfg.setFileOutConfigList(focList);
    86. mpg.setCfg(cfg);
    87. // 配置模板
    88. TemplateConfig templateConfig = new TemplateConfig();
    89. // 配置自定义输出模板
    90. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    91. // templateConfig.setEntity("templates/entity2.java");
    92. // templateConfig.setService();
    93. // templateConfig.setController();
    94. templateConfig.setXml(null);
    95. mpg.setTemplate(templateConfig);
    96. // 策略配置
    97. StrategyConfig strategy = new StrategyConfig();
    98. strategy.setNaming(NamingStrategy.underline_to_camel);
    99. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    100. strategy.setEntityLombokModel(true);
    101. strategy.setRestControllerStyle(true);
    102. // 公共父类
    103. // 写于父类中的公共字段
    104. strategy.setControllerMappingHyphenStyle(true);
    105. mpg.setStrategy(strategy);
    106. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    107. mpg.execute();
    108. }
    109. }

    5.举个例子

    混合使用mp代码生成器+swagger+联表查询

     

    5.1 依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.bootgroupId>
    4. <artifactId>spring-boot-starter-webartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>com.baomidougroupId>
    8. <artifactId>mybatis-plus-boot-starterartifactId>
    9. <version>3.4.2version>
    10. dependency>
    11. <dependency>
    12. <groupId>com.baomidougroupId>
    13. <artifactId>mybatis-plus-generatorartifactId>
    14. <version>3.4.1version>
    15. dependency>
    16. <dependency>
    17. <groupId>org.apache.velocitygroupId>
    18. <artifactId>velocity-engine-coreartifactId>
    19. <version>2.3version>
    20. dependency>
    21. <dependency>
    22. <groupId>org.freemarkergroupId>
    23. <artifactId>freemarkerartifactId>
    24. <version>2.3.30version>
    25. dependency>
    26. <dependency>
    27. <groupId>com.spring4allgroupId>
    28. <artifactId>swagger-spring-boot-starterartifactId>
    29. <version>1.9.1.RELEASEversion>
    30. dependency>
    31. <dependency>
    32. <groupId>com.github.xiaoymingroupId>
    33. <artifactId>swagger-bootstrap-uiartifactId>
    34. <version>1.7.8version>
    35. dependency>
    36. <dependency>
    37. <groupId>mysqlgroupId>
    38. <artifactId>mysql-connector-javaartifactId>
    39. <scope>runtimescope>
    40. dependency>
    41. <dependency>
    42. <groupId>org.projectlombokgroupId>
    43. <artifactId>lombokartifactId>
    44. <optional>trueoptional>
    45. dependency>
    46. <dependency>
    47. <groupId>org.springframework.bootgroupId>
    48. <artifactId>spring-boot-starter-testartifactId>
    49. <scope>testscope>
    50. dependency>
    51. dependencies>

    5.2 自动生成测试类

    1. // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
    2. public class CodeGenerator {
    3. /**
    4. *

    5. * 读取控制台内容
    6. *

    7. */
    8. public static void main(String[] args) {
    9. // 代码生成器
    10. AutoGenerator mpg = new AutoGenerator();
    11. // 全局配置
    12. GlobalConfig gc = new GlobalConfig();
    13. gc.setOutputDir("./src/main/java");
    14. gc.setAuthor("wd");
    15. gc.setOpen(false);
    16. gc.setSwagger2(true); //实体属性 Swagger2 注解
    17. mpg.setGlobalConfig(gc);
    18. // 数据源配置
    19. DataSourceConfig dsc = new DataSourceConfig();
    20. dsc.setUrl("jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai");
    21. // dsc.setSchemaName("public");
    22. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    23. dsc.setUsername("root");
    24. dsc.setPassword("123456");
    25. mpg.setDataSource(dsc);
    26. // 包配置
    27. PackageConfig pc = new PackageConfig();
    28. pc.setModuleName("autiomp");
    29. pc.setParent("com.qy151wd");
    30. mpg.setPackageInfo(pc);
    31. // 自定义配置
    32. InjectionConfig cfg = new InjectionConfig() {
    33. @Override
    34. public void initMap() {
    35. // to do nothing
    36. }
    37. };
    38. // 如果模板引擎是 freemarker
    39. String templatePath = "/templates/mapper.xml.ftl";
    40. // 如果模板引擎是 velocity
    41. // String templatePath = "/templates/mapper.xml.vm";
    42. // 自定义输出配置
    43. List focList = new ArrayList<>();
    44. // 自定义配置会被优先输出
    45. focList.add(new FileOutConfig(templatePath) {
    46. @Override
    47. public String outputFile(TableInfo tableInfo) {
    48. tableInfo.setName(tableInfo.getName().replace("tbl_",""));
    49. //tableInfo.setEntityName(tableInfo.getEntityName().replace("Tbl",""));
    50. tableInfo.setControllerName(tableInfo.getControllerName().replace("Tbl",""));
    51. tableInfo.setServiceName(tableInfo.getServiceName().replace("Tbl",""));
    52. tableInfo.setServiceImplName(tableInfo.getServiceImplName().replace("Tbl",""));
    53. tableInfo.setMapperName(tableInfo.getMapperName().replace("Tbl",""));
    54. tableInfo.setXmlName(tableInfo.getXmlName().replace("Tbl",""));
    55. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
    56. return "./src/main/resources/mapper/"
    57. + "/" + tableInfo.getEntityName().replace("Tbl","") + "Mapper" + StringPool.DOT_XML;
    58. }
    59. });
    60. /*
    61. cfg.setFileCreate(new IFileCreate() {
    62. @Override
    63. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
    64. // 判断自定义文件夹是否需要创建
    65. checkDir("调用默认方法创建的目录,自定义目录用");
    66. if (fileType == FileType.MAPPER) {
    67. // 已经生成 mapper 文件判断存在,不想重新生成返回 false
    68. return !new File(filePath).exists();
    69. }
    70. // 允许生成模板文件
    71. return true;
    72. }
    73. });
    74. */
    75. cfg.setFileOutConfigList(focList);
    76. mpg.setCfg(cfg);
    77. // 配置模板
    78. TemplateConfig templateConfig = new TemplateConfig();
    79. // 配置自定义输出模板
    80. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    81. // templateConfig.setEntity("templates/entity2.java");
    82. // templateConfig.setService();
    83. // templateConfig.setController();
    84. templateConfig.setXml(null);
    85. mpg.setTemplate(templateConfig);
    86. // 策略配置
    87. StrategyConfig strategy = new StrategyConfig();
    88. strategy.setNaming(NamingStrategy.underline_to_camel);
    89. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    90. strategy.setEntityLombokModel(true);
    91. strategy.setRestControllerStyle(true);
    92. // 公共父类
    93. // 写于父类中的公共字段
    94. strategy.setControllerMappingHyphenStyle(true);
    95. mpg.setStrategy(strategy);
    96. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    97. mpg.execute();
    98. }
    99. }

    5.3 启动类

    1. @SpringBootApplication
    2. @EnableSwagger2
    3. @MapperScan(value = "com.qy151wd.autiomp.mapper")
    4. public class AutiompApplication {
    5. public static void main(String[] args) {
    6. SpringApplication.run(AutiompApplication.class, args);
    7. }
    8. }

    5.4 配置类

    5.4.1 MybatisPlusConfig

    1. @Configuration
    2. public class MybatisPlusConfig {
    3. /**
    4. * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
    5. */
    6. @Bean
    7. public MybatisPlusInterceptor mybatisPlusInterceptor() {
    8. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    9. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    10. return interceptor;
    11. }
    12. }

    5.4.2 MyMetaObjectHandler

    1. @Slf4j
    2. @Component
    3. public class MyMetaObjectHandler implements MetaObjectHandler {
    4. @Override//当添加时自动填充的值
    5. public void insertFill(MetaObject metaObject) {
    6. log.info("start insert fill ....");
    7. this.strictInsertFill(metaObject, "gmtCreated", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
    8. }
    9. @Override //当修改时自动填充的值d
    10. public void updateFill(MetaObject metaObject) {
    11. log.info("start update fill ....");
    12. this.strictUpdateFill(metaObject, "gmtUpdated", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
    13. }
    14. }

    5.5 controller层(自动生成)

    5.6 entity层(自动生成,部分进行修改)

    5.6.1 TblDept

    1. @Data
    2. @EqualsAndHashCode(callSuper = false)
    3. @ApiModel(value="TblDept对象", description="")
    4. @TableName(value = "tbl_dept")
    5. public class TblDept implements Serializable {
    6. private static final long serialVersionUID = 1L;
    7. @ApiModelProperty(value = "部门编号")
    8. @TableId(value = "did", type = IdType.AUTO)
    9. private Integer did;
    10. @ApiModelProperty(value = "部门名称")
    11. private String dName;
    12. }

    5.6.2 User

    1. @Data
    2. @EqualsAndHashCode(callSuper = false)
    3. @ApiModel(value="User对象", description="")
    4. public class User implements Serializable {
    5. private static final long serialVersionUID = 1L;
    6. @ApiModelProperty(value = "主键ID")
    7. @TableId(value = "id", type = IdType.AUTO)
    8. private Integer id;
    9. @ApiModelProperty(value = "姓名")
    10. private String name;
    11. @ApiModelProperty(value = "年龄")
    12. private Integer age;
    13. @ApiModelProperty(value = "邮箱")
    14. private String email;
    15. @ApiModelProperty(value = "逻辑列0代表未删除,1代表已删除")
    16. @TableLogic//逻辑列
    17. private Boolean isdeleted;
    18. @ApiModelProperty(value = "创建时间")
    19. @TableField(fill = FieldFill.INSERT)
    20. private LocalDateTime gmtCreated;
    21. @ApiModelProperty(value = "更新时间")
    22. @TableField(fill = FieldFill.UPDATE)
    23. private LocalDateTime gmtUpdated;
    24. @ApiModelProperty(value = "部门id")
    25. @TableField(exist = false)
    26. private TblDept tblDept;
    27. }

    5.7 Mapper层(自动生成)

    添加联表查询后进行分页输出:UserMapper

    1. public interface UserMapper extends BaseMapper {
    2. IPage selectUserWithDept(IPage page, @Param("ew") Wrapper wrapper);
    3. }

    5.8 service层(自动生成)

    5.9 mapper层

    5.10 Mapper层(自动生成)

    添加联表查询:UserMapper.xml

    1. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    2. <mapper namespace="com.qy151wd.autiomp.mapper.UserMapper">
    3. <resultMap id="baseMapper" type="com.qy151wd.autiomp.entity.User" autoMapping="true">
    4. <id column="id" property="id"/>
    5. <result property="gmtCreated" column="gmt_created"/>
    6. <result property="gmtUpdated" column="gmt_updated"/>
    7. <association property="tblDept" javaType="com.qy151wd.autiomp.entity.TblDept" autoMapping="true">
    8. <id column="deptId" property="did"/>
    9. association>
    10. resultMap>
    11. <sql id="allChose">
    12. id,name,age,email,isdeleted,gmt_created,gmt_updated,u.did,d.did deptId,d.dname
    13. sql>
    14. <select id="selectUserWithDept" resultMap="baseMapper">
    15. select <include refid="allChose"/> from user u join tbl_dept d on u.did=d.did where isdeleted=0
    16. <if test="ew!=null">
    17. and ${ew.sqlSegment}
    18. if>
    19. select>
    20. mapper>

    5.11 application.properties配置

    1. spring.datasource.password=123456
    2. spring.datasource.username=root
    3. spring.datasource.url=jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    5. //sql日志
    6. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    7. #指定映射文件的路径
    8. mybatis.mapper-locations=classpath:mapper/*Mapper.xml
    9. spring.mvc.pathmatch.matching-strategy=ant_path_matcher

  • 相关阅读:
    【Web3 系列开发教程——创建你的第一个 NFT(8)】如何开发一个成功的 NFT 项目 | NFT 社区建设技巧
    Java枚举详解
    牛客-超级跳
    c++的3D游戏笔录-基于panda3d(2)
    大数据培训—DolphinScheduler(三)
    《代码大全2》第4章 关键的“构建“决策
    30天Python入门(第七天:深入了解Python中的集合)
    机器人中的数值优化(十六)—— 约束优化的应用:控制分配问题、碰撞距离计算、非线性MPC
    基于51单片机的智能遥控晾衣架温度湿度光强检测proteus仿真原理图PCB
    Nginx部署history路由模式的vue项⽬
  • 原文地址:https://blog.csdn.net/qq_50896786/article/details/126010363