springboot整合mybatis-plus逆向工程(代码片段)

smfx1314 smfx1314     2022-12-08     700

关键词:

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 [email protected]
2 Jack 20 [email protected]
3 Tom 28 [email protected]
4 Sandy 21 [email protected]
5 Billie 24 [email protected]

其对应的数据库 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, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

初始化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: [email protected]
 * @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简介mybatis增强工具包,简化CRUD操作。文档http://mp.baomidou.comhttp://mybatis.plus优点|Advantages无侵入:Mybatis-Plus在Mybatis的基础上进行扩展,只做增强不做改变,引入Mybatis-Plus不会对您现有的Mybatis构架产生任何影响... 查看详情

springboot整合mybatis-plus+durid数据库连接池(代码片段)

...及项目搭建springboot整合之版本号统一管理  springboot整合mybatis-plus+durid数据库连接池springboot整合swaggerspringboot整合mybatis代码快速生成springboot整合之统一结果返回springboot整合之统一异常处理springboot整合之Validated参数校验 sprin... 查看详情

实践丨springboot整合mybatis-plus项目存在mapper时报错

​摘要:​在SpringBoot运行测试Mybatis-Plus测试的时候报错的问题分析与修复本文分享自华为云社区《​​SpringBoot整合MybatisPlus项目存在Mapper时运行报错的问题分析与修复​​》,作者:攻城狮Chova。异常信息在SpringBoot运行测试Mybat... 查看详情

第276天学习打卡(知识点回顾springboot整合mybatis-plus)

知识点回顾springboot整合Mybatis-plus自动配置MyBatisPlusAutoConfiguration配置类,MyBatisPlusProperties配置项绑定。mybatis-plus:xxx就是对mybatis-plus的定制SqlSessionFactory自动配置好,底层是容器中默认的数据源mapperLocations自动配置好的。有... 查看详情

springboot整合mybatis-plus

maven依赖注意:本文使用的是mysql,数据库依赖就不展示了<!--引入mvbatie-plusstarter--> <dependency> <groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><versi 查看详情

springboot使用druid与mybatis-plus整合(代码片段)

SpringBoot使用Druid与Mybatis-plus整合需要导入的依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependenc 查看详情

springboot2.x:整合mybatis-plus

简介Mybatis-Plus是在Mybatis的基础上,国人开发的一款持久层框架。并且荣获了2018年度开源中国最受欢迎的中国软件TOP5同样以简化开发为宗旨的SpringBoot与Mybatis-Plus放在一起会产生什么样的化学反应呢?下面我们来领略一下两者配... 查看详情

实践丨springboot整合mybatis-plus项目存在mapper时报错

...#xff0c;作者:攻城狮Chova。异常信息在SpringBoot运行测试Mybatis-Plus测试的时候报错:rg.springframework.beans.factory.UnsatisfiedDependencyException:Errorcreatin 查看详情

springboot整合mybatis-plus

1.添加pom引用maven的引用很简单,官方已经给出starter,不需要我们考虑它的依赖关系了,此处使用的是2.3版本。<dependency>  <groupId>com.baomidou</groupId>  <artifactId>mybatis-plus-boot-starter</artif 查看详情

使用springboot+gradle快速整合mybatis-plus

作者:Stanley罗昊QQ:1164110146MyBatis-Plus(简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。注:作者使用IDEA编辑器使用SpringInitializr快速初始化一个SpringBoot工程在IDEA编辑左上角Fli... 查看详情

springboot整合mybatis-plus+druid组件,实现增删改查

前言本篇文章主要介绍的是SpringBoot整合mybatis-plus,实现增删改查。GitHub源码链接位于文章底部。建库建表创建springboot数据库,创建t_user表,字段id主键自增,name,age。工程结构添加依赖新建一个maven项目,在pom文件中添加以下依... 查看详情

springboot整合mybatis-plus逆向工程(代码片段)

MyBatis-Plus(简称MP)是一个?MyBatis?的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。官方文档代码生成器AutoGenerator是MyBatis-Plus的代码生成器,通过AutoGenerator可以快速生成Entity、Mapper、MapperXML、Service... 查看详情

springboot整合mybatis-plus(代码片段)

...用三、减少硬编码四、代码生成器写在前面        mybatis-plus顾名思义就是mybatis的增强工具。对于mybatis的功能只做扩展、不做改变。体现在内置的Mapper对CRUD进行了封装、只需要通过简单的配置即可实现增删改查操作。而不... 查看详情

springboot整合mongodb操作工具类仿mybatis-plus风格(代码片段)

以下是仿照mybatis-plus风格操作mongodb的增删改查的工具类以及使用示例 pom文件引入依赖<!--mongodb--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb< 查看详情

使用springboot简单整合springsecurity和mybatis-plus(代码片段)

1、概述SpringSecurity是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的实际标准。SpringSecurity是一个框架,致力于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Sprin... 查看详情

一文吃透springboot整合mybatis-plus(保姆式教程)(代码片段)

...心性养成之路🥭本文内容:一文吃透SpringBoot整合mybatis-plus(保姆式教程)文章目录手动整合mybatis-plus详解1、引入依赖2、创建基本目录结构3、配置application.yml4、在entity包下创建实体类5、创建Mapper接口6、创建Mappe... 查看详情

springboot整合mybatis-plus分页自动填充功能(代码片段)

springboot整合Mybatis-Plus分页、自动填充功能功能此次分页、自动填充功能的实现是在SpringBoot整合druid、Mybatis-plus实现的基础上完成的,包括数据源配置、各种依赖添加、mapper和service的实现。不在重复记录。Java开发手册要求数... 查看详情

mybatis-plus的操作(新增,修改)(代码片段)

一、springboot整合mybatis-plus1.1springboot在整合mybatis-plus时,pom文件中的坐标一般同时会引入Druid。<!--springboot整合mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><ver... 查看详情