springboot 集成 mybatis-plus 代码生成器

springboot 集成 mybatis-plus 代码生成器

  • 一、导入坐标依赖
  • 二、配置快速代码生成器
  • 三、自定义代码生成器模板

一、导入坐标依赖

前置依赖,需要用到 mybatis,mysql驱动,lombok插件以及swapper.(因为后面接口测试文档,所以swapper也配了)

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.3.1version>
dependency>


<dependency>
    <groupId>com.mysqlgroupId>
    <artifactId>mysql-connector-jartifactId>
    <scope>runtimescope>
dependency>

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-boot-starterartifactId>
    <version>3.0.0version>
dependency>

mybatis-plus 代码生成器的依赖,mybatis-plus生成器依赖于mybatis-plus


<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.5.3.1version>
dependency>

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-generatorartifactId>
    <version>3.5.3.1version>
dependency>

<dependency>
    <groupId>org.apache.velocitygroupId>
    <artifactId>velocity-engine-coreartifactId>
    <version>2.3version>
dependency>

二、配置快速代码生成器

package com.robin.codegenerator.utils;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;

import java.sql.Types;
import java.util.Collections;

/*
* 代码生成器配置类
*/
public class CodeGenerator {

    public static void main(String[] args) {
        generator();
    }

    public static void generator(){
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/robin?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false",
                                 "root", "root")
            .globalConfig(builder -> {
                builder.author("robin") // 设置作者
                    .enableSwagger() // 开启 swagger 模式
                    .fileOverride() // 覆盖已生成文件
                    .outputDir("D:\\IdeaProjects\\CodeGenerator\\src\\main\\java"); // 指定输出目录
            })
            .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                if (typeCode == Types.SMALLINT) {
                    // 自定义类型转换
                    return DbColumnType.INTEGER;
                }
                return typeRegistry.getColumnType(metaInfo);

            }))
            .packageConfig(builder -> {
                builder.parent("com.robin.codegenerator") // 设置父包名
                    .moduleName(null) // 设置父包模块名
                    .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\IdeaProjects\\CodeGenerator\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
            })
            .strategyConfig(builder -> {                    
                builder.controllerBuilder().enableHyphenStyle(); // 开启驼峰转连字符
                builder.controllerBuilder().enableRestStyle(); //开启生成@RestController 控制器
                builder.entityBuilder().enableLombok(); // 配置lombok 对实体类的策略配置Lombok的getter setter
                builder.addInclude("sys_user") // 设置需要生成的表名
                    .addTablePrefix("sys_", "t_"); // 设置过滤表前缀

            })
            //                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
            .execute();
    }
}

三、自定义代码生成器模板

自定义代码生成器模板,需要我们找到依赖中代码生成器的模板配置文件。(以自定义controller的生成器模板为例子)

盘符:\仓库地址\com\baomidou\mybatis-plus-generator\3.5.3.1\mybatis-plus-generator-3.5.3.1.jar!\templates\controller.java.vm

springboot 集成 mybatis-plus 代码生成器_第1张图片

自己需要定义哪些模板就找到对应的文件,copy一份到resources/templates目录下

springboot 集成 mybatis-plus 代码生成器_第2张图片



package ${package.Controller};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

import $!{package.Service}.$!{table.serviceName};
import ${package.Entity}.${entity};

#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * 

* $!{table.comment} 前端控制器 *

* * @author ${author} * @since ${date} */
#if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${kotlin}) class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end #else #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass} { #else public class ${table.controllerName} { #end @Resource private ${table.serviceName} ${table.entityPath}Service; @PostMapping public Boolean save(@RequestBody ${entity} ${table.entityPath}) { return ${table.entityPath}Service.saveOrUpdate(${table.entityPath}); } @DeleteMapping("/{id}") public Boolean delete(@PathVariable Integer id) { return ${table.entityPath}Service.removeById(id); } @GetMapping public List<${entity}> findAll() { return ${table.entityPath}Service.list(); } //批量删除 @PostMapping("/del/batch") public boolean deleteBatch(@RequestBody List<Integer> ids){ return ${table.entityPath}Service.removeBatchByIds(ids); } @GetMapping("/page") public Page<${entity}> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) { IPage<User> page = new Page<>(pageNum,pageSize); QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc("id"); return ${table.entityPath}Service.page(new Page<>(pageNum, pageSize),QueryWrapper); } } #end

运行生成的controller对比如下:

springboot 集成 mybatis-plus 代码生成器_第3张图片

代码生成器运行后的项目目录树:

springboot 集成 mybatis-plus 代码生成器_第4张图片

你可能感兴趣的:(springboot随笔,spring,boot,mybatis,后端)