springboot整合mybatisPlus自动生成代码

1.依赖

<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.20</version>
	</dependency>

	<!--自动生成代码依赖包-->
	<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-boot-starter</artifactId>
		<version>3.4.2</version>
	</dependency>


	<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-generator</artifactId>
		<version>3.4.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-validation</artifactId>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
	<dependency>
		<groupId>org.freemarker</groupId>
		<artifactId>freemarker</artifactId>
		<version>2.3.31</version>
	</dependency>

2.配置文件:generatorConfig.properties

generator.jdbc.driverClass=com.mysql.cj.jdbc.Driver
generator.jdbc.url=jdbc:mysql://192.168.100.171:32692/lossReduction_syl?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
generator.jdbc.username=root
generator.jdbc.password=nydndev

#包名
projectPackage=com.zyp
#生成到该项目空间下面(与代码是同级目录)-->代码文件生成之后直接复制到对应位置即可
outputFilePath=/mybatisPlus/src/main/java/com/zyp/
outputMapXmlFilePath=/mybatisPlus/src/main/resources/mapper/

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

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

3.工具类

package com.zyp.util;

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 syl
 */
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");

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor("syl");
        // 是否打开输出目录
        gc.setOpen(false);
        // 输出文件目录
        gc.setOutputDir(projectPath+"/mybatisPlus" + "/src/main/java");
        // 是否覆盖已有文件
        gc.setFileOverride(true);
        // 实体属性 Swagger2 注解
        gc.setSwagger2(true);
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        // mapper.xml中生成BaseResultMap
        gc.setBaseResultMap(true);
        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/entity";
                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();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值