springboot整合mybatis-plus逆向工程的实现

 更新时间:2020年9月1日 08:18  点击:1895

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。官方文档

代码生成器

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

mybatis-plus是根据数据库表来生成对应的实体类,首先我们创建数据库表User

id name age email
1 Jone 18 test1@baomidou.com
2 Jack 20 test2@baomidou.com
3 Tom 28 test3@baomidou.com
4 Sandy 21 test4@baomidou.com
5 Billie 24 test5@baomidou.com

其对应的数据库 Schema 脚本如下:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

其对应的数据库 Data 脚本如下:

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

初始化springboot工程


其中mpconfig就是我们逆向工程配置文件

基本依赖如下:

<dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
  </dependency>
 </dependencies>

下面开始引入逆向工程依赖

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

  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.1.1</version>
  </dependency>
  <!--添加 代码生成器 依赖-->
  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.1.1</version>
  </dependency> 

添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。

Velocity(默认):

<dependency>
 <groupId>org.apache.velocity</groupId>
 <artifactId>velocity-engine-core</artifactId>
 <version>2.1</version>
</dependency>

Freemarker:

<dependency>
 <groupId>org.freemarker</groupId>
 <artifactId>freemarker</artifactId>
 <version>2.3.28</version>
</dependency>

这里我选择Freemarker
注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎

全部依赖如下:

<dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>

  <!-- freemarker 模板引擎 -->
  <dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.23</version>
  </dependency>
  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.1.1</version>
  </dependency>
  <!--添加 代码生成器 依赖-->
  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.1.1</version>
  </dependency>
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
 </dependencies>

下面开始:创建逆向工程配置类mpconfig

package com.jiangfeixiang.mpdemo.mpconfig;

import com.baomidou.mybatisplus.annotation.DbType;
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.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
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.*;

/**
 * @ProjectName: mybatis-plus
 * @Package: com.jiangfeixiang.mybatisplus.mpconfig
 * @ClassName: CodeGenerator
 * @Author: jiangfeixiang
 * @email: 1016767658@qq.com
 * @Description: 代码生成器
 * @Date: 2019/5/10/0010 21:41
 */
public class CodeGenerator {

 /**
  * 读取控制台内容
  */
 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 globalConfig = new GlobalConfig();
  //生成文件的输出目录
  String projectPath = System.getProperty("user.dir");
  globalConfig.setOutputDir(projectPath + "/src/main/java");
  //Author设置作者
  globalConfig.setAuthor("姜飞祥");
  //是否覆盖文件
  globalConfig.setFileOverride(true);
  //生成后打开文件
  globalConfig.setOpen(false);
  mpg.setGlobalConfig(globalConfig);

  /**
   * 数据源配置
   */
  DataSourceConfig dataSourceConfig = new DataSourceConfig();
  // 数据库类型,默认MYSQL
  dataSourceConfig.setDbType(DbType.MYSQL);
  //自定义数据类型转换
  dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
  dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false");
  dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
  dataSourceConfig.setUsername("root");
  dataSourceConfig.setPassword("1234");
  mpg.setDataSource(dataSourceConfig);

  /**
   * 包配置
   */
  PackageConfig pc = new PackageConfig();
  pc.setModuleName(scanner("模块名"));
  //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
  pc.setParent("com.jiangfeixiang.mpdemo");
  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();

  // 配置自定义输出模板
  //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  // templateConfig.setEntity("templates/entity2.java");
  // templateConfig.setService();
  // 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.setInclude(scanner("表名,多个英文逗号分割").split(","));
  //实体是否为lombok模型(默认 false)
  strategy.setEntityLombokModel(true);
  //生成 @RestController 控制器
  strategy.setRestControllerStyle(true);
  //设置自定义继承的Entity类全称,带包名
  //strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity");
  //设置自定义继承的Controller类全称,带包名
  //strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController");
  //设置自定义基础的Entity类,公共字段
  strategy.setSuperEntityColumns("id");
  //驼峰转连字符
  strategy.setControllerMappingHyphenStyle(true);
  //表名前缀
  strategy.setTablePrefix(pc.getModuleName() + "_");
  mpg.setStrategy(strategy);
  mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  mpg.execute();
 }
}

拆分详解如下:

/**
  * 读取控制台内容
  */
 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 + "!");
 }

读取控制台内容无需更改,因为稍后启动main方法只会需要在控制台输入模块名以及数据库表名。官网参考
接下来是main方法,这个也是主程序,逆向工程启动方法。下面看一下配置

AutoGenerator mpg = new AutoGenerator();

代码生成器,所有的配置都需要set进去

全局配置:

GlobalConfig globalConfig = new GlobalConfig();
  //生成文件的输出目录(下面两行无需改动)
  String projectPath = System.getProperty("user.dir");
  globalConfig.setOutputDir(projectPath + "/src/main/java");
  //Author设置作者
  globalConfig.setAuthor("姜飞祥");
  //是否覆盖文件
  globalConfig.setFileOverride(true);
  //生成后打开文件
  globalConfig.setOpen(false);
  //set进去代码生成器对象中
  mpg.setGlobalConfig(globalConfig);

数据源配置

 DataSourceConfig dataSourceConfig = new DataSourceConfig();
  // 数据库类型,默认MYSQL
  dataSourceConfig.setDbType(DbType.MYSQL);
  //自定义数据类型转换
  dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
  //驱动,URL,用户名以及密码配置,这里使用的是mysql5.6版本
  dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false");
  dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
  dataSourceConfig.setUsername("root");
  dataSourceConfig.setPassword("1234");
  //set进去代码生成器对象中
  mpg.setDataSource(dataSourceConfig);

包配置

PackageConfig pc = new PackageConfig();
  //这里的模块名需要在控制台输入的,即生成的代码在哪个包下
  pc.setModuleName(scanner("模块名"));
  //父包名。如果为空子包名必须写全部, 否则就只需写子包名
  pc.setParent("com.jiangfeixiang.mpdemo");
  //set进去代码生成器对象中
  mpg.setPackageInfo(pc);

上面父包名是根据工程路径来的,如下参考:

自定义配置

InjectionConfig cfg = new InjectionConfig() {
   @Override
   public void initMap() {
    // to do nothing
   }
  };

自定义输出配置

String templatePath = "/templates/mapper.xml.ftl";
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;
   }
  });
  //这块是set到上面自定义配置中
  cfg.setFileOutConfigList(focList);
  //set进去代码生成器对象中
  mpg.setCfg(cfg);

最后是策略配置

StrategyConfig strategy = new StrategyConfig();
  //设置命名格式
  strategy.setNaming(NamingStrategy.underline_to_camel);
  strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
  //实体是否为lombok模型(默认 false)
  strategy.setEntityLombokModel(true);
  //生成 @RestController 控制器
  strategy.setRestControllerStyle(true);
  //设置自定义继承的Entity类全称,带包名
  //strategy.setSuperEntityClass("com.jiangfeixiang.mpdemo.BaseEntity");
  //设置自定义继承的Controller类全称,带包名
  //strategy.setSuperControllerClass("com.jiangfeixiang.mpdemo.BaseController");
  //设置自定义基础的Entity类,公共字段
  strategy.setSuperEntityColumns("id");
  //驼峰转连字符
  strategy.setControllerMappingHyphenStyle(true);
  //表名前缀
  strategy.setTablePrefix(pc.getModuleName() + "_");
  mpg.setStrategy(strategy);
  mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  mpg.execute();

以上全部配置好之后直接启动main方法,之后进入控制台


我的模块名是springbootmp,因为我有两张表,输入两个表的名称回车即可生成对应的代码,所生成的代码在模块名springbootmp下

正确执行控制台输出如下

然后看一下模块:


xxxmapper.xml文件是空的:


实体类已经加上@Data注解省略了get/set方法并序列化


mapper接口继承了BaseMapper


接口中没有数据的增删改查方法,那么我们直接在UserController类中注入IUserService接口,查询所有user看看有没有输出:

@RestController
@RequestMapping("/springbootmp/user")
public class UserController {

 @Autowired
 private IUserService iUserService;

 /**
  * 获取所有User
  * @return
  */
 @RequestMapping("/getAllUser")
 public List<User> getAllUser(){
  List<User> list = iUserService.list();
  return list;
 }

}

项目运行直接报错如下:


原因是因为主程序中没有加入@MapperScan("com.jiangfeixiang.mpdemo.springbootmp.mapper")

引入即可。之后重新运行启动成功控制台如下图:


还有mybatisplus是不是很漂亮。
调用接口测试如下

源码

到此这篇关于springboot整合mybatis-plus逆向工程的实现的文章就介绍到这了,更多相关springboot mybatis-plus逆向工程内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • mybatis-plus 表名添加前缀的实现方法

    这篇文章主要介绍了mybatis-plus 表名添加前缀的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-08-26
  • mybatis-plus 返回部分字段的解决方式

    这篇文章主要介绍了mybatis-plus 返回部分字段的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-02
  • MyBatis-Plus自动填充功能失效导致的原因及解决

    这篇文章主要介绍了MyBatis-Plus自动填充功能失效导致的原因及解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • mybatis-plus 处理大数据插入太慢的解决

    这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
  • 解决mybatis-plus 查询耗时慢的问题

    这篇文章主要介绍了解决mybatis-plus 查询耗时慢的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-04
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • 使用mybatis-plus报错Invalid bound statement (not found)错误

    这篇文章主要介绍了使用mybatis-plus报错Invalid bound statement (not found)错误,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-02
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • mybatis-plus实体类主键策略有3种(小结)

    这篇文章主要介绍了mybatis-plus实体类主键策略有3种(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-08-27
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • mybatis-plus  mapper中foreach循环操作代码详解(新增或修改)

    这篇文章主要介绍了mybatis-plus mapper中foreach循环操作代码详解(新增或修改),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-17
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • mybatis-plus getOne和逻辑删除问题详解

    这篇文章主要介绍了mybatis-plus getOne和逻辑删除,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-08-26