mybatisPlus自动生成代码

                     参考文章

本文完全是参考↑↑参考文章

通过这个配置可以生成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中了) 

 

第二步,自动生成的配置文件 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

 对应项目中的位置

 

第三步、生成器代码 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();
    }
}

我放在项目中的对应位置

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

需要修改的地方

1.generatorConfig.properties

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

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是一款优秀的MyBatis框架的增强工具包,它为MyBatis提供了许多强大的功能,其中就包括自动生成代码的功能。 使用MyBatis-Plus自动生成代码的步骤如下: 1. 首先在项目的pom.xml文件中添加MyBatis-Plus的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> ``` 2. 在application.yml或application.properties文件中配置MyBatis-Plus的自动生成代码的相关配置,例如: ```yaml # 数据源配置 spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: root # MyBatis-Plus配置 mybatis-plus: # 实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.example.demo.entity # XML文件路径 mapperLocations: classpath:/mapper/*.xml # 自动填充配置 global-config: db-config: # 自动填充配置 field-strategy: not_null # 数据库主键自增策略 id-type: auto # 字段名下划线转驼峰 column-underline: true # 代码生成器配置 generator: # 生成文件输出目录 output-dir: src/main/java # 是否覆盖已有文件 fileOverride: true # 是否开启swagger注解 swagger2: true # 自定义文件命名,注意 %s 会自动填充表实体属性! entity-name: %sEntity mapper-name: %sMapper xml-name: %sMapper service-name: %sService service-impl-name: %sServiceImpl controller-name: %sController # 指定生成的表名,多个表名用逗号分隔 include: user, role # 排除生成的表名,多个表名用逗号分隔 exclude: test, demo # 自定义继承的Entity类全称,带包名 super-entity-class: com.example.demo.common.BaseEntity # 自定义继承的Mapper类全称,带包名 super-mapper-class: com.example.demo.common.BaseMapper # 自定义继承的Service类全称,带包名 super-service-class: com.example.demo.common.BaseService # 自定义继承的ServiceImpl类全称,带包名 super-service-impl-class: com.example.demo.common.BaseServiceImpl # 自定义继承的Controller类全称,带包名 super-controller-class: com.example.demo.common.BaseController # 是否去掉生成实体时生成的get、set方法 entity-boolean-logic: false # 是否支持 ActiveRecord 模式 active-record: true # 是否生成实体时,生成字段注解 entity-column-annotation-enable: true # 是否生成 @RestController 控制器 rest-controller-style: true ``` 3. 在项目中创建一个代码生成器的类,例如: ```java package com.example.demo.generator; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; public class CodeGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); gc.setAuthor("your name"); gc.setOpen(false); gc.setFileOverride(true); gc.setActiveRecord(false); gc.setEnableCache(false); gc.setBaseResultMap(true); gc.setBaseColumnList(true); gc.setIdType(IdType.AUTO); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.example.demo"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.impl"); pc.setController("controller"); 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.setControllerMappingHyphenStyle(true); strategy.setInclude("user", "role"); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); // 执行生成 mpg.execute(); } } ``` 4. 运行代码生成器的main方法即可自动生成代码。 注意:在执行代码生成器之前,需要先创建好对应的数据库表。另外,生成的代码需要进行适当的修改和优化,以符合实际的业务需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值