通过这个配置可以生成mapper.xml,mapper,serviceImpl,controller等等

大概介绍一下,主要分为几个部分

首先,就是依赖

第二,就是一个自动生成代码需要的配置类generatorConfig.properties (修改这个表里的配置可以改变你要生成实体的表名,位置等等)

第三,就是生成器代码

第四,最重要的一步,把我的配置文件改成你的,目录改成你的(如果你不知道怎么改,建议直接在main方法入口打个断点,慢慢调试,就明白了)

好了,下面开始上代码

第一,pom中需要加入的依赖

<!-- mybatisPlus-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

      <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

      <!--swagger 文档-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

(我的项目时多模块项目,我把这个的依赖放在parent的pom.xml中了) 

mybaties 自动生成 配置Clob mybatisplus自动生成代码_java

 

第二步,自动生成的配置文件 generatorConfig.properties

generator.jdbc.driverClass=com.mysql.cj.jdbc.Driver
generator.jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
generator.jdbc.username=root
generator.jdbc.password=123456

projectPackage=com.luoyu.service
#下面两个字段都是从项目名开始填
outputFilePath=/luoyu-demo-service/src/main/java/com/luoyu/service/
outputMapXmlFilePath=/luoyu-demo-service/src/main/resources/mapper/

# 表名 多表之间逗号分隔
tableNames=user

# 包配置
setMapper=mapper
setEntity=model
setService=service
setController=controller

 对应项目中的位置

mybaties 自动生成 配置Clob mybatisplus自动生成代码_java_02

 

第三步、生成器代码 CodeGenerator

package com.luoyu.service.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Project code genertor
 *
 * @author zjx
 */
public class CodeGenerator {


    /**
     * Project package
     */
    private static String projectPackage;

    private static String outputFilePath;

    private static String outputMapXmlFilePath;

    private static String tableNames;

    /**
     * 包配置
     */
    private static String setMapper;
    private static String setEntity;
    private static String setService;
    private static String setController;

    /**
     * Database url
     */
    private static String url;
    /**
     * Database username
     */
    private static String username;
    /**
     * Database password
     */
    private static String password;
    /**
     * Database driver class
     */
    private static String driverClass;

    /**
     * 文件名后缀
     */
    private static String fileSuffix = ".java";

    /**
     * Init database information
     */
    static {
        Properties properties = new Properties();
        InputStream i = CodeGenerator.class.getResourceAsStream("/generatorConfig.properties");
        try {
            properties.load(i);
            url = properties.getProperty("generator.jdbc.url").trim();
            username = properties.getProperty("generator.jdbc.username").trim();
            password = properties.getProperty("generator.jdbc.password").trim();
            driverClass = properties.getProperty("generator.jdbc.driverClass").trim();
            projectPackage = properties.getProperty("projectPackage").trim();
            outputFilePath = properties.getProperty("outputFilePath").trim();
            outputMapXmlFilePath = properties.getProperty("outputMapXmlFilePath").trim();
            tableNames = properties.getProperty("tableNames").trim();
            setMapper = properties.getProperty("setMapper").trim();
            setEntity = properties.getProperty("setEntity").trim();
            setService = properties.getProperty("setService").trim();
            setController = properties.getProperty("setController").trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * main method, execute code generator
     */
    public static void main(String[] args) {
        String projectPath = System.getProperty("user.dir");

        String javaPath = projectPackage.replaceAll("\\.", "/");
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor("luoyu");
//        gc.setOpen(false); // 是否打开输出目录,设置为true就是直接弹出生成的文件目录
//        gc.setOutputDir(projectPath + "/src/main/java"); // 输出文件目录
        gc.setFileOverride(false); // 是否覆盖已有文件
        gc.setSwagger2(true);  // 实体属性 Swagger2 注解
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setBaseResultMap(true); // mapper.xml中生成BaseResultMap
        gc.setActiveRecord(true);
        gc.setBaseColumnList(true);

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url.trim());
        //dsc.setSchemaName("public");
        dsc.setUsername(username.trim());
        dsc.setPassword(password.trim());
        dsc.setDriverName(driverClass.trim());

        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(projectPackage.trim());
        //pc.setModuleName("model名"); 自定义包名
        pc.setMapper(setMapper.trim());
        pc.setEntity(setEntity.trim());
        pc.setService(setService.trim());
        pc.setController(setController.trim());
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();

        /**mapper xml文件*/
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {

            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + outputMapXmlFilePath + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }

        });
        /**控制层*/
        templatePath = "/templates/controller.java.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + outputFilePath + "controller";
                String entityFile = String.format(expand + File.separator + "%s" + fileSuffix, tableInfo.getControllerName());
                return entityFile;
            }
        });

        /**业务接口层*/
        templatePath = "/templates/service.java.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + outputFilePath + "service";
                String entityFile = String.format(expand + File.separator + "%s" + fileSuffix, tableInfo.getServiceName());
                return entityFile;
            }
        });
        /**业务实现层*/
        templatePath = "/templates/serviceImpl.java.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + outputFilePath + "service/impl";
                String entityFile = String.format(expand + File.separator + "%s" + fileSuffix, tableInfo.getServiceImplName());
                return entityFile;
            }
        });

        /**数据mapper层*/
        templatePath = "/templates/mapper.java.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + outputFilePath + "mapper";
                String entityFile = String.format(expand + File.separator + "%s" + fileSuffix, tableInfo.getMapperName());
                return entityFile;
            }
        });

        /**数据entity层*/
        templatePath = "/templates/entity.java.ftl";
        // 自定义配置会优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + outputFilePath + "model";
                String entityFile = String.format(expand + File.separator + "%s" + fileSuffix, tableInfo.getEntityName());
                return entityFile;
            }
        });

		/*cfg.setFileOutConfigList(new IFileCreate() {
			@Override
			public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
				// 判断自定义文件夹是否需要创建
				checkDir("调用默认方法创建目录");
				return false;
			}
		});*/

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

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

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //strategy.setExclude("");
        // 表名
        strategy.setInclude(tableNames.split(","));
        strategy.setControllerMappingHyphenStyle(true);
        /**表前缀,要自动去除添加*/
        //strategy.setTablePrefix("t_");

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
    }
}

我放在项目中的对应位置

mybaties 自动生成 配置Clob mybatisplus自动生成代码_java_03

 第四步、记得去修改成你本地的对应配置哦 

需要修改的地方

1.generatorConfig.properties

mybaties 自动生成 配置Clob mybatisplus自动生成代码_bc_04

2.codeGenerator中类似于下图圈中的地方(就是实际配置目录的地方)

mybaties 自动生成 配置Clob mybatisplus自动生成代码_java_05

好了,记录一下,以防以后现找,正好大家一起学习