需要如下部分:
- 生成代码的控制器
- 生成代码的模板引擎
- 生成代码的模板
mybatisPlus和模板引擎的jar包坐标可以在官网处直接复制
参考文章:
代码生成器(官网)
代码生成器&自定义controller 模板
自定义代码模板
1. 生成代码的控制器
可以理解为对模板进行填空,主要包括:生成代码器、全局配置、数据源配置、包配置、策略配置。当然中间还有其它很多配置未涉及。
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.Scanner;
public class GenerateCode {
public static void main(String[] args) {
solution();
}
static void solution() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入模块名,没有则不输入");
String modelName = scanner.nextLine();
System.out.println("请输入表名,多个表用逗号隔开,全部直接回车");
String tablesName = scanner.nextLine();
//1.创建代码生成器
AutoGenerator mpg = new AutoGenerator();
//2.全局配置:https://www.bookstack.cn/read/mybatis-plus-3.x/spilt.6.4267953fc3057caf.md
GlobalConfig gc = new GlobalConfig();//用于设置全局配置相关参数
String projectPath;
if (modelName.length() >= 1){
projectPath = System.getProperty("user.dir") + "\\" + modelName + "\\src\\main\\java";//获取java目录地址
}else {
projectPath=System.getProperty("user.dir") + "\\src\\main\\java";
}
gc.setOutputDir(projectPath);//文件输出目录
gc.setAuthor("itcast");//作者
gc.setOpen(false);//生成后是否打开文件
gc.setFileOverride(true);//覆盖已有文件
gc.setIdType(IdType.AUTO);//主键的Id类型
gc.setServiceName("%sService");//默认首字母会是I,这里通过自定义来把Service接口首字母I去除
gc.setDateType(DateType.ONLY_DATE);//设置日期类型
gc.setBaseColumnList(true);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//3.数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL)
.setDriverName("com.mysql.cj.jdbc.Driver")
.setUrl("jdbc:mysql://52.83.215.238:3306/test")
.setUsername("root")
.setPassword("cqaBSL!Z8cf7^BU@");
mpg.setDataSource(dsc);
// 4.包配置:包名
PackageConfig pc = new PackageConfig();
// pc.setModuleName(modelName);//设置模块的名字
pc.setParent("com.itcast");//设置包名
pc.setEntity("entity");//设置实体类包名
pc.setController("controller");
pc.setMapper("mapper");
pc.setService("service");
mpg.setPackageInfo(pc);
//5.策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库映射到实体类时下划线转驼峰的策略
if (tablesName.length() >= 1) {
strategy.setInclude(tablesName.split(","));//要映射的表的表名
}
strategy.setTablePrefix("tb_");//--类名不生成表的前缀ab_
strategy.setEntityLombokModel(true);//自动添加Lombok注解
//逻辑删除
// strategy.setLogicDeleteFieldName("is_deleted");//--指定逻辑删除字段名
// strategy.setEntityBooleanColumnRemoveIsPrefix(true);//--去除布尔值类型字段名字的is_前缀
strategy.setRestControllerStyle(true);//restfull风格
// strategy.setVersionFieldName("version");//设置乐观锁的咧
mpg.setStrategy(strategy);
// 默认Velocity(默认),选择 freemarker 引擎需要指定如下,注意 pom依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
//指定自定义模板文件
TemplateConfig templateConfig = new TemplateConfig()
.setController("templates/controller.java")
.setServiceImpl("templates/serviceImpl.java");
mpg.setTemplate(templateConfig);
mpg.execute();
// mybatisplusTest01
// tb_growth_rule
}
}
2. 模板引擎
模板引擎,提供了代码生成器相关等等的API,MyBatis-Plus 支持有Velocity(默认)、Freemarker、Beetl。也可以自己定义,不过一般不自定义。MyBatis-Plus 从3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖。
3. 模板
主要有Controller、Service、ServiceImpl、Mapper、Entity,每个模板引擎对应一个类型的模板,Freemarker简单、学习的资源多一点。注意,不管是哪个模板引擎,对应的代码生成器的API都是一样的,只是模板表达不同而已。
Freemarker语法参考:
Freemarker 语法详解
FreeMarker 中文官方参考手册
1. controller.java.vm
package ${package.Controller};//包名
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.*;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import ${package.Entity}.PageVO;
import java.util.*;
import javax.annotation.Resource;
## ====类======
/**
*
* @author ${author}
* @since ${date}
*/
@Api(tags = {"$!{table.comment}" })
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end" )
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
## =======方法体======
## 注意这里用名字的话,@service()应该也指定,所以对应模板也改一下。
@Resource(name = "${table.serviceImplName}")
public ${table.serviceName} ${entity}Service;
/**
* 分页查询
*/
@ApiOperation(value = "查询分页数据" )
@GetMapping(value = "/pagelist/{page}/{pagesize}" )
public PageVO<${entity}> findListByPage(@PathVariable Long page,@PathVariable Long pagesize,@RequestParam Map searchMap){
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<${entity}>();
if(searchMap != null && !searchMap.isEmpty()){
queryWrapper.allEq(searchMap);
}
IPage<${entity}> ipage = ${entity}Service.page(
new Page<${entity}>(page,pagesize),
queryWrapper);
return new PageVO<${entity}>(ipage);
}
/**
* 根据id查询
*/
@ApiOperation(value = "根据id查询数据" )
@GetMapping(value = "/{id}" )
public ${entity} getById(@PathVariable("id") String id){
return ${entity}Service.getById(id);
}
/**
* 新增
*/
@ApiOperation(value = "新增数据")
@PostMapping(value = "/" )
public void add(@RequestBody ${entity} ${entity}){
${entity}Service.save(${entity});
}
/**
* 删除
*/
@ApiOperation(value = "删除数据")
@DeleteMapping(value = "/{id}")
public void delete(@PathVariable("id") String id){
${entity}Service.removeById(id);
}
/**
* 更新数据
*/
@ApiOperation(value = "更新数据")
@PutMapping(value = "/{id}")
public void update(@PathVariable("id" ) String id, @RequestBody ${entity} ${entity}){
${entity}Service.updateById(${entity});
}
}
2. controller.java.ftl
package ${package.Controller};
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.*;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import ${package.Entity}.PageVO;
import javax.annotation.Resource;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@Api(tags = {"${table.comment!}"})
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
//注意这里用名字的话,@service()应该也指定,所以对应模板也改一下。
@Resource(name = "${table.serviceImplName?uncap_first}")
public ${table.serviceName} ${entity?uncap_first}Service;
/**
* 分页查询
*/
@ApiOperation(value = "查询分页数据" )
@GetMapping(value = "/pagelist/{page}/{pagesize}" )
public PageVO<${entity}> findListByPage(@PathVariable Long page,@PathVariable Long pagesize,@RequestParam Map searchMap){
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<${entity}>();
if(searchMap != null && !searchMap.isEmpty()){
queryWrapper.allEq(searchMap);
}
IPage<${entity}> ipage = ${entity?uncap_first}Service.page(
new Page<${entity}>(page,pagesize),
queryWrapper);
return new PageVO<${entity}>(ipage);
}
/**
* 根据id查询
*/
@ApiOperation(value = "根据id查询数据" )
@GetMapping(value = "/{id}" )
public ${entity} getById(@PathVariable("id") String id){
return ${entity?uncap_first}Service.getById(id);
}
/**
* 新增
*/
@ApiOperation(value = "新增数据")
@PostMapping(value = "/" )
public void add(@RequestBody ${entity} ${entity?uncap_first}){
${entity?uncap_first}Service.save(${entity?uncap_first});
}
/**
* 删除
*/
@ApiOperation(value = "删除数据")
@DeleteMapping(value = "/{id}")
public void delete(@PathVariable("id") String id){
${entity?uncap_first}Service.removeById(id);
}
/**
* 更新数据
*/
@ApiOperation(value = "更新数据")
@PutMapping(value = "/{id}")
public void update(@PathVariable("id" ) String id, @RequestBody ${entity} ${entity?uncap_first}){
${entity?uncap_first}Service.updateById(${entity?uncap_first});
}
}
</#if>