如何利用Mybatis-Plus自动生成代码(超详细注解)

阳光穿透心脏的1/2处 2023-09-26 23:34 168阅读 0赞

如何利用Mybatis-Plus自动生成代码(超详细注解)

      • 1、简介
      • 2、代码生成器
      • 3、详细使用教程
        • 3.1 两个mysql数据库:
        • 3.2 创建springboot项目
        • 3.3 添加依赖
        • 3.5 编辑application.yml文件
        • 3.6 主启动类
      • 4、运行
        • 4.1 项目最终结构
        • 4.2 运行代码生成器类
        • 4.3 测试运行controller

1、简介

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
在这里插入图片描述

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

支持数据库

任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss
,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift

达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库,优炫数据库

2、代码生成器

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

  1. /**
  2. * <p>
  3. * mysql 代码生成器
  4. * </p>
  5. */
  6. public class CodeGenerator {
  7. /**
  8. * 运行启动
  9. */
  10. public static void main(String[] args) {
  11. //获取控制台的数据
  12. Scanner scanner = new Scanner(System.in);
  13. // 代码生成器
  14. AutoGenerator mpg = new AutoGenerator();
  15. //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~开始~~~~~~~~~
  16. GlobalConfig gc = new GlobalConfig();
  17. //System.out.println("请输入文件输出目录的模块或者项目的地址:");
  18. //String projectPath = scanner.nextLine();
  19. String projectPath = System.getProperty("user.dir"); //工程根目录
  20. System.out.println(projectPath);
  21. gc.setOutputDir(projectPath + "/src/main/java"); //生成文件的输出目录
  22. gc.setAuthor("tigerhhzz"); //作者
  23. gc.setFileOverride(true); //是否覆蓋已有文件 默认值:false
  24. gc.setOpen(false); //是否打开输出目录 默认值:true
  25. gc.setBaseColumnList(true); //开启 baseColumnList 默认false
  26. gc.setBaseResultMap(true); //开启 BaseResultMap 默认false
  27. //gc.setEntityName("%sEntity"); //实体命名方式 默认值:null 例如:%sEntity 生成 UserEntity
  28. gc.setMapperName("%sMapper"); //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
  29. gc.setXmlName("%sMapper"); //Mapper xml 命名方式 默认值:null 例如:%sDao 生成 UserDao.xml
  30. gc.setServiceName("%sService"); //service 命名方式 默认值:null 例如:%sBusiness 生成 UserBusiness
  31. gc.setServiceImplName("%sServiceImpl"); //service impl 命名方式 默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
  32. gc.setControllerName("%sController"); //controller 命名方式 默认值:null 例如:%sAction 生成 UserAction
  33. mpg.setGlobalConfig(gc);
  34. //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~结束~~~~~~~~~
  35. //~~~~~~~~~~~~~~~~~~~~~数据源配置~~~~~~~~~~开始~~~~~~~~~
  36. DataSourceConfig dsc = new DataSourceConfig();
  37. dsc.setUrl("jdbc:mysql://localhost:3306/tigervueblog?useUnicode=true&useSSL=false&characterEncoding=utf8");
  38. // dsc.setSchemaName("public");
  39. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
  40. dsc.setUsername("root");
  41. dsc.setPassword("123456");
  42. mpg.setDataSource(dsc);
  43. //~~~~~~~~~~~~~~~~~~~~~数据源配置~~~~~~~~~~结束~~~~~~~~~
  44. //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~开始~~~~~~~~~
  45. PackageConfig pc = new PackageConfig();
  46. // pc.setModuleName(scanner("模块名"));
  47. // pc.setParent("com.stu");
  48. System.out.println("请输入模块名:");
  49. String name = scanner.nextLine();
  50. //自定义包配置
  51. pc.setParent(name);
  52. pc.setModuleName(null);
  53. pc.setMapper("mapper");
  54. pc.setEntity("domain");
  55. pc.setService("service");
  56. pc.setServiceImpl("service.impl");
  57. pc.setController("controller");
  58. mpg.setPackageInfo(pc);
  59. //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~结束~~~~~~~~~
  60. //~~~~~~~~~~~~~~~~~~~~~自定义配置~~~~~~~~~~开始~~~~~~~~~
  61. InjectionConfig cfg = new InjectionConfig() {
  62. @Override
  63. public void initMap() {
  64. // to do nothing
  65. }
  66. };
  67. List<FileOutConfig> focList = new ArrayList<>();
  68. focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
  69. @Override
  70. public String outputFile(TableInfo tableInfo) {
  71. // 自定义输入文件名称
  72. return projectPath + "/src/main/resources/mapper/" + /*pc.getModuleName() + "/" +*/
  73. tableInfo.getEntityName() + "Mapper" +
  74. StringPool.DOT_XML;
  75. }
  76. });
  77. cfg.setFileOutConfigList(focList);
  78. mpg.setCfg(cfg);
  79. //~~~~~~~~~~~~~~~~~~~~~自定义配置~~~~~~~~~~结束~~~~~~~~~
  80. //这里不自动生成xml,改为自定义生成
  81. mpg.setTemplate(new TemplateConfig().setXml(null));
  82. //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~开始~~~~~~~~~
  83. // 策略配置 数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
  84. StrategyConfig strategy = new StrategyConfig();
  85. strategy.setNaming(NamingStrategy.underline_to_camel); //表名生成策略
  86. strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
  87. // strategy.setCapitalMode(true); // 全局大写命名 ORACLE 注意
  88. // strategy.setTablePrefix("prefix"); //表前缀
  89. // strategy.setSuperEntityClass("com.stu.domain"); //自定义继承的Entity类全称,带包名
  90. // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); //自定义实体,公共字段
  91. strategy.setEntityLombokModel(true); //【实体】是否为lombok模型(默认 false
  92. strategy.setRestControllerStyle(true); //生成 @RestController 控制器
  93. // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); //自定义继承的Controller类全称,带包名
  94. // strategy.setInclude(scanner("表名")); //需要包含的表名,允许正则表达式(与exclude二选一配置)
  95. System.out.println("请输入映射的表名(多个表名英文逗号分割):");
  96. String tables = scanner.nextLine();
  97. String[] num = tables.split(",");
  98. strategy.setInclude(num); // 需要生成的表可以多张表
  99. // strategy.setExclude(new String[]{"test"}); // 排除生成的表
  100. //如果数据库有前缀,生成文件时是否要前缀acl_
  101. // strategy.setTablePrefix("bus_");
  102. // strategy.setTablePrefix("sys_");
  103. strategy.setControllerMappingHyphenStyle(true); //驼峰转连字符
  104. strategy.setTablePrefix(pc.getModuleName() + "_"); //是否生成实体时,生成字段注解
  105. mpg.setStrategy(strategy);
  106. //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~结束~~~~~~~~~
  107. //模板引擎配置,使用Freemarker,默认 Velocity 可选模板引擎 Beetl\
  108. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  109. mpg.execute();
  110. }
  111. }

3、详细使用教程

3.1 两个mysql数据库:

m_user脚本:

  1. CREATE TABLE `m_user` (
  2. `id` bigint NOT NULL AUTO_INCREMENT COMMENT '自动递增id',
  3. `username` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
  4. `avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户头像',
  5. `email` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '邮箱地址',
  6. `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
  7. `status` int NOT NULL DEFAULT '0' COMMENT '0代表正常,-1代表被锁定',
  8. `created` datetime DEFAULT NULL COMMENT '注册时间',
  9. `last_login` datetime DEFAULT NULL COMMENT '最后登录时间',
  10. PRIMARY KEY (`id`),
  11. KEY `UK_USERNAME` (`username`) USING BTREE
  12. ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

m_blog脚本:

  1. CREATE TABLE `m_blog` (
  2. `id` bigint NOT NULL AUTO_INCREMENT,
  3. `user_id` bigint NOT NULL,
  4. `title` varchar(255) NOT NULL,
  5. `description` varchar(255) NOT NULL,
  6. `content` longtext,
  7. `created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  8. `status` tinyint DEFAULT NULL,
  9. PRIMARY KEY (`id`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
3.2 创建springboot项目

在这里插入图片描述

3.3 添加依赖

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

项目完整pom文件:(注意版本号)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.6.6</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.tigerhhzz</groupId>
  12. <artifactId>springboot-mybatisplus-demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-mybatisplus-demo</name>
  15. <description>Demo project for Spring Boot MP</description>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter</artifactId>
  20. </dependency>
  21. <!-- 包含spirng Mvc ,tomcat的包包含requestMapping restController 等注解 -->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-actuator</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-aop</artifactId>
  38. </dependency>
  39. <!--mysql数据库 -->
  40. <dependency>
  41. <groupId>mysql</groupId>
  42. <artifactId>mysql-connector-java</artifactId>
  43. <version>8.0.28</version>
  44. </dependency>
  45. <!-- druid 连接池 -->
  46. <!-- <dependency>-->
  47. <!-- <groupId>com.alibaba</groupId>-->
  48. <!-- <artifactId>druid</artifactId>-->
  49. <!-- <version>1.2.8</version>-->
  50. <!-- </dependency>-->
  51. <!-- mybatis版本必须与druid版本兼容,否则无法创建DataSource -->
  52. <dependency>
  53. <groupId>com.baomidou</groupId>
  54. <artifactId>mybatis-plus-boot-starter</artifactId>
  55. <version>3.2.0</version>
  56. </dependency>
  57. <!-- 引入freemarker模板引擎供mp生成代码-->
  58. <dependency>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-starter-freemarker</artifactId>
  61. </dependency>
  62. <!--mp代码生成器-->
  63. <dependency>
  64. <groupId>com.baomidou</groupId>
  65. <artifactId>mybatis-plus-generator</artifactId>
  66. <version>3.3.0</version>
  67. </dependency>
  68. <!-- hutool工具类-->
  69. <dependency>
  70. <groupId>cn.hutool</groupId>
  71. <artifactId>hutool-all</artifactId>
  72. <version>5.3.3</version>
  73. </dependency>
  74. <!-- lombok注解-->
  75. <dependency>
  76. <groupId>org.projectlombok</groupId>
  77. <artifactId>lombok</artifactId>
  78. <optional>true</optional>
  79. </dependency>
  80. <!-- 日志打印-->
  81. <dependency>
  82. <groupId>log4j</groupId>
  83. <artifactId>log4j</artifactId>
  84. <version>1.2.12</version>
  85. </dependency>
  86. <!-- 单元测试-->
  87. <dependency>
  88. <groupId>junit</groupId>
  89. <artifactId>junit</artifactId>
  90. <version>4.12</version>
  91. </dependency>
  92. </dependencies>
  93. <build>
  94. <plugins>
  95. <plugin>
  96. <groupId>org.springframework.boot</groupId>
  97. <artifactId>spring-boot-maven-plugin</artifactId>
  98. <configuration>
  99. <excludes>
  100. <exclude>
  101. <groupId>org.projectlombok</groupId>
  102. <artifactId>lombok</artifactId>
  103. </exclude>
  104. </excludes>
  105. </configuration>
  106. </plugin>
  107. </plugins>
  108. </build>
  109. </project>
3.5 编辑application.yml文件
  1. server:
  2. port: 8082
  3. servlet:
  4. context-path: /
  5. spring:
  6. datasource:
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. # test-mybatis
  9. url: jdbc:mysql://127.0.0.1:3306/tigervueblog?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
  10. username: root
  11. password: 123456
  12. jackson:
  13. date-format: yyyy-MM-dd HH:mm:ss
  14. time-zone: GMT+8
  15. serialization:
  16. write-dates-as-timestamps: false
  17. mybatis-plus:
  18. configuration:
  19. map-underscore-to-camel-case: true
  20. auto-mapping-behavior: full
  21. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  22. mapper-locations: classpath*:mapper/**/*Mapper.xml
  23. global-config:
  24. # �߼�ɾ������
  25. db-config:
  26. # ɾ��ǰ
  27. logic-not-delete-value: 1
  28. # ɾ����
  29. logic-delete-value: 0
3.6 主启动类
  1. package com.mpautocode;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. /**
  6. * @author tigerhhzz
  7. * @date 2023/4/28 9:16
  8. */
  9. @Slf4j
  10. @SpringBootApplication
  11. public class springbootmptest {
  12. public static void main(String[] args) {
  13. SpringApplication.run(springbootmptest.class, args);
  14. log.info("springbootmptest启动成功~~~~^…^~~~~^…^~~~~~^…^~~~~");
  15. }
  16. }

4、运行

4.1 项目最终结构

在这里插入图片描述

4.2 运行代码生成器类

在这里插入图片描述
输入模块名:
在这里插入图片描述

请输入映射的表名(多个表名英文逗号分割):
在这里插入图片描述
生成完成
在这里插入图片描述

4.3 测试运行controller

在运行主启动类之前,检查在生成好的mapper接口中加入@Mapper注解。

编写一个usercontroller

  1. package com.mpautocode.controller;
  2. import com.mpautocode.domain.MUser;
  3. import com.mpautocode.service.MUserService;
  4. import com.tigerhhzz.springbootmybatisplusdemo.entities.CommonResult;
  5. import com.tigerhhzz.springbootmybatisplusdemo.entities.User;
  6. import com.tigerhhzz.springbootmybatisplusdemo.service.UserService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import java.util.List;
  12. /**
  13. * <p>
  14. * 前端控制器
  15. * </p>
  16. *
  17. * @author tigerhhzz
  18. * @since 2023-04-28
  19. */
  20. @RestController
  21. @RequestMapping("/m-user")
  22. public class MUserController {
  23. @Autowired
  24. MUserService userService;
  25. /**
  26. * list(查询所有)
  27. * @return
  28. */
  29. @GetMapping("/list")
  30. public CommonResult list(){
  31. // 查询所有
  32. List<MUser> list = userService.list();
  33. return new CommonResult(200,"查询数据成功",list);
  34. }
  35. }

运行结果:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,168人围观)

还没有评论,来说两句吧...

相关阅读