mybatisPlus生成基础代码

MyBatisPlus生成基础代码实例

mybatisPlus生成基础代码实例

前提:基于mybatisPlus 版本3.5.12;
生成类包括entity,mapper,mapper.xml,service,serviceImpl,controller,dto,vo。生成的文件都可以自定义目录。
1 引入依赖;

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.12</version>
</dependency>

2 主要执行类

package com.ws.utb.generator;

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

import java.io.File;
import java.sql.Types;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class CodeGeneratoreNew {
    public static void main(String[] args) {

        String rootDir = System.getProperty("user.dir")+"/spring-boot-demo";
        String outputDir = rootDir + File.separator + "src/main/java";
        String xmlDir = rootDir + File.separator + "src/main/resources/mapper";
        
        //自定义输出路径,只能定义OutputFile中文件类型的路径
        HashMap<OutputFile, String> pathInfo = new HashMap<>();
        /*pathInfo.put(OutputFile.controller, outputDir + File.separator + "com/ws/utb/boot/demo/control");
        pathInfo.put(OutputFile.serviceImpl, outputDir + File.separator + "com/ws/utb/boot/demo/db/service/impl");*/
        pathInfo.put(OutputFile.xml, xmlDir);


        FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/ws_demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&nullCatalogMeansCurrent=true&useSSL=true&serverTimezone=GMT%2B8&tinyInt1isBit=true", "root", "password")
                // 全局配置
                .globalConfig((scanner, builder) -> builder.author(scanner.apply("请输入作者名称?"))
                        .enableSwagger()
                        .outputDir(outputDir)
                        .disableOpenDir())

                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.TINYINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )

                // 包配置,配置父级+模块
                .packageConfig((scanner, builder) -> builder.parent("com.ws.utb.boot.demo")
                        .moduleName("module_name") //模块名
                        .pathInfo(pathInfo))
                // 模板配置,配置其他的生成文件
                .injectionConfig(builder -> {
                    builder.customMap(new HashMap<String, Object>(){{
                        put("dtoPackage", "com.ws.utb.boot.demo.bean.dto");//定义包路径
                        put("voPackage", "com.ws.utb.boot.demo.bean.vo");
                    }});
                    builder.customFile(file -> {
                        file.fileName("DTO.java")                     // 生成文件名规则
                                .templatePath("/templates/entityDTO.java.ftl") // 模板路径
                                .filePath(outputDir + File.separator + "com/ws/utb/boot/demo/bean/dto");// 输出文件目录
                    });
                    builder.customFile(file -> {
                        file.fileName("VO.java")                     // 生成文件名规则
                                .templatePath("/templates/entityVO.java.ftl") // 模板路径
                                .filePath(outputDir + File.separator + "com/ws/utb/boot/demo/bean/vo");          // 输出文件目录
                    });
                })

                // 策略配置
                .strategyConfig((scanner, builder) -> builder
                        .addTablePrefix(scanner.apply("表前缀"))
                        .addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
                        .entityBuilder()
                        .enableLombok()
                        .enableActiveRecord()
                        .enableFileOverride()
                        .enableChainModel()
                        .naming(NamingStrategy.underline_to_camel)
                        .columnNaming(NamingStrategy.underline_to_camel)
                        .enableTableFieldAnnotation()
                        .controllerBuilder() // 生成controller
                        .enableRestStyle()
                        .enableHyphenStyle()
                        .build())
                // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                //下面这些可以不用指定,新版已废弃,模板放在resources/templates下,会默认引用;模板名称默认为模板名称,
                // 如Controller.java.ftl,Service.java.ftl,ServiceImpl.java.ftl,Entity.java.ftl,Mapper.java.ftl,Mapper.xml.ftl
              /*  .templateConfig(config -> {
                    config.controller("/templates/Controller.java"); // 指定模板路径
                })*/
                .execute();
    }


    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}

3 创建ftl模板例子
注:1生成的Service接口名前面默认带大写的i;
2引入包的路径之类的根据项目实际详情改下;
3生成的文件如果需要每次覆盖需要在strategyConfig中配置;
4 模板中特殊格式需要满足Freemarker格式要求,可以使用assign 方式拼接;

如controller每次生成覆盖:

    .controllerBuilder()
     .enableFileOverride()
package com.ws.utb.boot.ws.control;

import java.util.List;
<#assign page = "Result<IPage<" + entity + "VO>>">
<#assign allPage = "Result<List<" + entity + "VO>>">
<#assign getById = "Result<" + entity + "VO>">

/**
* <p>
    * ${table.comment!} 前端控制器
    * </p>
*
* @author ${author}
* @since ${date}
*/
@RestController
@RequestMapping("/${table.entityPath}")
@Api(tags = "${table.comment!}管理")
public class ${table.controllerName} {

    @Autowired
    private I${entity}Service service;

    @ApiOperation(value = "查询分页数据", httpMethod = "POST")
    @PostMapping("/listPage")
    public ${page} listPage(@Validated @RequestBody ${entity}DTO dTO) {
        return Result.getSuccessResult(service.listPage(dTO));
    }

    @ApiOperation(value = "查询详情", httpMethod = "GET")
    @GetMapping("/{id}")
    public ${getById} getInfoById(@PathVariable Long id) {
        return Result.getSuccessResult(service.getInfoById(id));
    }

    @ApiOperation(value = "新增", httpMethod = "POST")
    @PostMapping("")
    public Result save(@Validated @RequestBody ${entity}DTO dTO) {
        return Result.getSuccessResult(service.save(dTO));
    }

    @ApiOperation(value = "更新", httpMethod = "POST")
    @PostMapping("/{id}")
    public Result update(@Validated @RequestBody ${entity}DTO dTO) {
        return Result.getSuccessResult(service.update(dTO));
    }

    @ApiOperation(value = "删除", httpMethod = "DELETE")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.getSuccessResult(service.delete(id));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值