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));
}
}
MyBatisPlus生成基础代码实例
3009

被折叠的 条评论
为什么被折叠?



