SpringBoot使用Mybatis-Plus Generator生成代码

阮华美
2023-12-01

概述

MyBatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

实现生成代码

maven依赖

 		 <properties>
        <mybatis-plus.version>3.2.0</mybatis-plus.version>
        <mysql.connector.java.version>8.0.19</mysql.connector.java.version>
        <springfox-swagger.version>2.9.2</springfox-swagger.version>
        <java.version>1.8</java.version>
    	</properties>

			<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.java.version}</version>
        </dependency>
		
			<!-- mybatis-plus依赖  start-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <!-- mybatis-plus依赖  end-->

			 <!-- swagger2  start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger.version}</version>
        </dependency>
        <!-- swagger2  end-->

			<!-- mybatisplus逆向工程需要模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

生成代码类

public class CodeGenerator {

    public static  String projectPath = null;

    public static void main(String[] args) {
        CodeGenerator codeGenerator = new CodeGenerator();
        codeGenerator.testGenerator();
    }

    public void testGenerator() {
        AutoGenerator mpg = new AutoGenerator();

        //1、全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor("zxk");   // 作者
        projectPath = System.getProperty("user.dir")+"/SpringBoot-Jwt-Examples";
        //        +"/SpringBoot-Jwt-Examples";
        gc.setEnableCache(false);// XML 二级缓存
        gc.setOutputDir(projectPath + "/src/main/java");

        gc.setOpen(false);      //生成代码后是否打开文件夹
        gc.setServiceName("%sService");  // 设置Service接口生成名称,这样生成接口前面就不会有 I
        mpg.setGlobalConfig(gc);

        //2、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        //3、包名策略配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName("sys"); // 模块名称, 这里可以根据不同模块来写
        pc.setParent("com.kang.springbootjwt"); // 父包名
        pc.setController("controller");
        pc.setService("service");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setXml("mapping");
        mpg.setPackageInfo(pc);

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

        // 如果模板引擎是 freemarker /templates/mapper.xml.ftl
        String templatePath = "/templates/mapper.xml.vm";

        // 自定义模板
        TemplateConfig template = new TemplateConfig();
        //设置模板
        template.setController("templates/controller.java");
//        template.setService("templates/service.java");
//        template.setServiceImpl("templates/serviceImpl.java");
//        template.setMapper("templates/mapper.java");
//        template.setXml("templates/mapper.xml");
//        template.setEntity("templates/entity.java");

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapping/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);

        //加入自定义模板配置
        mpg.setTemplate(template);

        //加入模板引擎
        //Freemarker模板引擎后缀为ftl
//        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        //Velocity模板引擎后缀为vm
        mpg.setTemplateEngine(new VelocityTemplateEngine());//默认模板引擎 new VelocityTemplateEngine()

        mpg.setCfg(cfg);


        //4、策略配置
        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("departments");  // 如果要生成多个table,这里可以传入String[]
        mpg.setStrategy(strategy);
        //5、执行
        mpg.execute();
    }
}

controller 模版

##package ${cfg.controllerPackage};
package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
##import ${package.Entity}.bo.QueryBO;
##import ${cfg.extPackagePre}.${cfg.service}.${table.serviceName};
##import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
##import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Package: ${package.Entity}.${entity}
 * @Description: <$!{table.comment}前端控制器>
 * @Author: ${author}
 * @CreateDate: ${date}
 * @UpdateUser: ${author}
 * @UpdateDate: ${date}
 * @UpdateRemark: <>
 * @Version: 1.0
 */
#set($path=${table.name})
#set($path=$path.concat("path"))
@RestController
##@Api(tags = "$!{table.comment}-相关接口")
@Api(tags = "${entity}-相关接口")
##@RequestMapping(value = "${cfg.get($path)}", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "${entity}")
public class ${table.controllerName} {

    private static final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    private ${table.serviceName} ${table.serviceName};

    @GetMapping("{id}")
    @ApiOperation(value = "$!{table.comment}获取某一实体")
    public ${entity} get${table.serviceName}Details(@PathVariable Integer id) {
        return ${table.serviceName}.getById(id);
    }

    @PostMapping
    @ApiOperation(value = "$!{table.comment}新增数据")
    public boolean save${table.serviceName}(@RequestBody ${entity} dto) {
        return ${table.serviceName}.save(dto);
    }

    @PutMapping("{id}")
    @ApiOperation(value = "$!{table.comment}修改数据")
    public boolean modify${table.serviceName}(@RequestBody ${entity} dto, @PathVariable Integer id) {
        dto.setId(id);
        return ${table.serviceName}.updateById(dto);
    }

    @DeleteMapping("batch")
    @ApiOperation(value = "$!{table.comment}批量删除数据")
    public boolean batchRemove${table.serviceName}(@RequestParam(value = "ids") List<Integer> ids) {
        return ${table.serviceName}.removeByIds(ids);
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "$!{table.comment}删除数据")
    public boolean remove${table.serviceName}(@PathVariable Integer id) {
        return ${table.serviceName}.removeById(id);
    }
}

参考

https://mp.baomidou.com/guide/generator.html

 类似资料: