Spring Boot中MyBatis-Plus代码生成器(三层架构简易代码生成)

  • Post author:
  • Post category:其他





MyBatis-Plus代码生成器(官网页面底部有配置解析)



https://baomidou.com/pages/779a6e/





MyBatis-Plus—代码生成器(非官方)



https://juejin.cn/post/7033399493684903949





Maven资源库查找对应资源版本



https://mvnrepository.com/



pom.xml依赖导入

<!-- 代码生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<!-- velocity模板 (mp包)-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>


MybatisPlusConfig(配置文件)

package com.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.example.dao")//包扫描
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

//    @Bean
//    public ConfigurationCustomizer configurationCustomizer() {
//        return configuration -> configuration.setUseDeprecatedExecutor(false);
//    }
}


CodeGenerator.java

package com.example.utils;

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

import java.util.Collections;

/**
 * mp代码生成器
 * by Carden
 * @since 2023-03-22
 */
public class CodeGenerator {

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

    private static void generate() {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/springbootvue?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&allowPublicKeyRetrieval=true
", "root", "123456")
                .globalConfig(builder -> {
                    builder.author("Carden") // 设置作者
//                          .enableSwagger() // 开启 swagger 模式(要先集成swagger才能生效)
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D:\\代码\\springboot\\src\\main\\java\\"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.example") // 设置父包名
                            .moduleName(null) // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\代码\\springboot\\src\\main\\resources\\mapper\\")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.entityBuilder().enableLombok();
                    builder.mapperBuilder().enableMapperAnnotation().build();//开启@mapper注释,若用包扫描则注释掉,默认false
                    builder.serviceBuilder().formatServiceFileName("%sService");//格式化 service 接口文件名称,%s进行匹配表名,如 UserService,默认为IUserService
                    builder.controllerBuilder().enableHyphenStyle()  // 开启驼峰转连字符
                            .enableRestStyle();  // 开启生成@RestController 控制器
                    builder.addInclude("sys_user") // 设置需要生成的表名(数据库中的)
                            .addTablePrefix("t_", "sys_"); // 设置过滤表前缀
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板(需要引入依赖)
                .execute();

    }
}



注:内容模板不是必需的,不自定义就按MyBatis-Plus自带的样式


自定义controller文件内容生成模板

(src/main/resources/templates/controller.java.vm)

package ${package.Controller};


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

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

#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController //拥有@ResponseBody+@Controller的作用 @ResponseBody将后台数据转为json数组返回前端
#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});
    }
    // 根据id删除数据
    @DeleteMapping("/delete${table.entityPath}/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return ${table.entityPath}Service.removeById(id);
    }
    // 根据多组id删除多组数据
    @PostMapping("/delete${table.entityPath}/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return ${table.entityPath}Service.removeByIds(ids);
    }
    // 查询所有数据
    @GetMapping("/queryAll")
    public List<${entity}> selectAll() {
        return ${table.entityPath}Service.list();
    }
    // 根据id查询数据
    @GetMapping("/query")
    public ${entity} selectByID(Integer id) {
        return ${table.entityPath}Service.getById(id);
    }
    // 根据页码,页面大小,分页查找
    @GetMapping("/queryByPage")
    public Page<${entity}> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return ${table.entityPath}Service.page(new Page<>(pageNum, pageSize), queryWrapper);
    }

}

#end


ps:同理mapper entity service的模板都可自定义,具体查看MyBatis-Plus的包

(com\baomidou\mybatis-plus-generator\3.5.1\mybatis-plus-generator-3.5.1.jar\templates\xxx.java.vm)


运行CodeGenerator.java中的main方法即可生成



版权声明:本文为qq_53762798原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。