Springboot Mybatis Plus自动生成工具类详解代码

 更新时间:2021年11月24日 15:12:27   作者:、Dong  
mybatis-plus 是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生,这篇文章带你使用Springboot Mybatis Plus自动生成工具类

前言

代码生成器,也叫逆向工程,是根据数据库里的表结构,自动生成对应的实体类、映射文件和接口。

看到很多小伙伴在为数据库生成实体类发愁,现分享给大家,提高开发效率。

一、pom依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

二、工具类

package com.his.utils;

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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Mybatis plus代码自动生成
 */
public class MybatisPlusUtil {
    /** 作者 */
    public static final String AUTHOR = "dd";

    /** 类命名 */
    /**
     * Entity命名
     */
    public static final String FILE_NAME_ENTITY = "%sEntity";
    /**
     * MAPPER命名
     */
    public static final String FILE_NAME_MAPPER = "%sMapper";
    /**
     * xml命名
     */
    public static final String FILE_NAME_XML = "%sMapper";
    /**
     * Service命名
     */
    public static final String FILE_NAME_SERVICE = "%sService";
    /**
     * ServiceImpl命名
     */
    public static final String FILE_NAME_SERVICE_IMPL = "%sDO";
    /**
     * Controller命名
     */
    public static final String FILE_NAME_CONTROLLER = "%sController";

    /**
     包命名,可以根据自己的项目情况自定义生成后的存放路径
     entity默认路径为父目录.entity
     mapper默认路径为父目录.mapper
     service默认路径为父目录.service
     serviceImpl默认路径为父目录.service.impl
     controller默认路径为父目录.controller
     */
    /**
     * PARENT命名
     */
    public static final String PACKAGE_NAME_PARENT = "com.his";
    /**
     * Entity命名
     */
    public static final String PACKAGE_NAME_ENTITY = "repository.entity.control";
    /**
     * MAPPER命名
     */
    public static final String PACKAGE_NAME_MAPPER = "repository.mapper.control";
    /**
     * xml命名
     */
    public static final String PACKAGE_NAME_XML = "sys";
    /**
     * Service命名
     */
    public static final String PACKAGE_NAME_SERVICE = "domain.control";
    /**
     * ServiceImpl命名
     */
    public static final String PACKAGE_NAME_SERVICE_IMPL = "domain.control";
    /**
     * Controller命名
     */
    public static final String PACKAGE_NAME_CONTROLLER = "facade.controller.control";

    /**
     * 读取控制台内容
     */
    private 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.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    /**
     * 运行这个main方法进行代码生成
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setFileOverride(true);
        gc.setAuthor(AUTHOR);
        gc.setOpen(false);
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);

        gc.setEntityName(FILE_NAME_ENTITY);
        gc.setMapperName(FILE_NAME_MAPPER);
        gc.setXmlName(FILE_NAME_XML);
        gc.setServiceName(FILE_NAME_SERVICE);
        gc.setServiceImplName(FILE_NAME_SERVICE_IMPL);
        gc.setControllerName(FILE_NAME_CONTROLLER);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:oracle:thin:@ip:port/test");
        dsc.setDriverName("oracle.jdbc.OracleDriver");
        dsc.setUsername("user");
        dsc.setPassword("pass");
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent(PACKAGE_NAME_PARENT);
        pc.setController(PACKAGE_NAME_CONTROLLER);
        pc.setService(PACKAGE_NAME_SERVICE);
        pc.setServiceImpl(PACKAGE_NAME_SERVICE_IMPL);
        pc.setMapper(PACKAGE_NAME_MAPPER);
        pc.setEntity(PACKAGE_NAME_ENTITY);
        pc.setXml(PACKAGE_NAME_XML);
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        // 设置表前缀
        strategy.setTablePrefix("IEMR_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 自定义配置
        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/"
                        + "/" + tableInfo.getMapperName() + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        mpg.execute();
    }
}

结尾

感谢大家的耐心阅读,如有建议请私信或评论留言。如有收获,劳烦支持,关注、点赞、评论、收藏均可,博主会经常更新,与大家共同进步

到此这篇关于Springboot Mybatis Plus自动生成工具类详解代码的文章就介绍到这了,更多相关Springboot Mybatis Plus 生成工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java中的多态和继承示例分析

    java中的多态和继承示例分析

    这篇文章主要介绍了java中的多态和继承,结合实例形式分析了java中的多态和继承原理、实现方法及相关操作注意事项,需要的朋友可以参考下
    2020-05-05
  • 详解spring boot mybatis全注解化

    详解spring boot mybatis全注解化

    这篇文章主要介绍了spring boot mybatis全注解化的相关资料,需要的朋友可以参考下
    2017-09-09
  • Java集合框架之Stack Queue Deque使用详解刨析

    Java集合框架之Stack Queue Deque使用详解刨析

    早在 Java 2 中之前,Java 就提供了特设类。比如:Dictionary, Vector, Stack, 和 Properties 这些类用来存储和操作对象组。虽然这些类都非常有用,但是它们缺少一个核心的,统一的主题。由于这个原因,使用 Vector 类的方式和使用 Properties 类的方式有着很大不同
    2021-10-10
  • 深入了解volatile和Java内存模型

    深入了解volatile和Java内存模型

    在本篇文章当中,主要给大家深入介绍Volatile关键字和Java内存模型。在文章当中首先先介绍volatile的作用和Java内存模型,然后层层递进介绍实现这些的具体原理、JVM底层是如何实现volatile的和JVM实现的汇编代码以及CPU内部结构,感兴趣的可以了解一下
    2022-08-08
  • Idea Jrebel 报错:Cannot reactivate,offline seat in use

    Idea Jrebel 报错:Cannot reactivate,offline 

    本文主要介绍了Idea Jrebel 报错:Cannot reactivate,offline seat in use,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • 详解Lombok的坑

    详解Lombok的坑

    这篇文章主要介绍了详解Lombok的坑,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Java8 Stream collect(Collectors.toMap())的使用

    Java8 Stream collect(Collectors.toMap())的使用

    这篇文章主要介绍了Java8 Stream collect(Collectors.toMap())的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • IDEA常量字符串过长问题及解决方案

    IDEA常量字符串过长问题及解决方案

    在编译Java项目时遇到“常量字符串过长”错误,可以通过修改编译器设置解决,具体方法是进入IDE的设置(File>>Settings>>Build, Execution, Deployment>>Compiler>>Java Compiler),将使用的编译器更改为Eclipse,如果问题依旧
    2024-10-10
  • 一文带你了解Java创建型设计模式之原型模式

    一文带你了解Java创建型设计模式之原型模式

    原型模式其实就是从一个对象在创建另外一个可定制的对象,不需要知道任何创建的细节。本文就来通过示例为大家详细聊聊原型模式,需要的可以参考一下
    2022-09-09
  • IntelliJ IDEA中折叠所有Java代码,再也不怕大段的代码了

    IntelliJ IDEA中折叠所有Java代码,再也不怕大段的代码了

    今天小编就为大家分享一篇关于IntelliJ IDEA中折叠所有Java代码,再也不怕大段的代码了,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10

最新评论