mybatis-plus代码⽣成器(Swagger2、⾃定义模板) ⼤佬新搭建的项⽬是mybatis—plus,因⽽⾃⼰学习使⽤下,对于这些固定的代码还是⼀键⽣成⽐较好。可根据模板⾃定义⽣成内容。maven依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
新建 GenerateMybatisPlus.java
import batisplus.annotation.DbType;
import batisplus.annotation.FieldFill;
import batisplus.annotation.IdType;
import ator.AutoGenerator;
import fig.*;
import fig.po.TableFill;
import fig.rules.DateType;
import fig.rules.NamingStrategy;
import ine.FreemarkerTemplateEngine;
import org.springframework.beans.factory.annotation.Value;
import org.t.properties.ConfigurationProperties;
import t.annotation.Configuration;
import t.annotation.PropertySource;
import st.context.TestPropertySource;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @description:
* @author: liyh
* @time: 2020/12/21 21:20
*/
/
/配置⽂件位置
public class GenerateMybatisPlus {
/**
* @param dataSourceurl
* @param dataSourcename
* @param dataSourcepassword
* @param dataSourcedriver
* @param tables
* @param packageParent
* @param isNormalize
* @description:
* @return: void
* @author: liyh
* @time: 2020/12/21 21:21
*/
public void generate(String dataSourceurl, String dataSourcename, String dataSourcepassword, String dataSourcedriver, String tables, String packageParent, boolean isNormalize) { AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = Property("user.dir");// 当前项⽬的路径
gc.setOutputDir(projectPath + "/src/main/java");// ⽣成⽂件输出根⽬录
gc.setAuthor("liyh");// 作者
gc.setOpen(false); // ⽣成完成后不弹出⽂件框
gc.setFileOverride(true); // ⽂件是否覆盖
gc.setIdType(IdType.ASSIGN_UUID); //主键策略实体类主键ID类型
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true); // 是否开启swagger
gc.setActiveRecord(true); //【不懂】活动记录不需要ActiveRecord特性的请改为false 是否⽀持AR模式
gc.setEnableCache(false);// XML ⼆级缓存
gc.setBaseResultMap(true);//【不懂】 XML ResultMap xml映射⽂件的配置
gc.setBaseColumnList(false);//【不懂】 XML columList xml映射⽂件的配置
// ⾃定义⽂件命名,注意 %s 会⾃动填充表实体属性!
gc.setControllerName("%sController");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
mpg.setGlobalConfig(gc);
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl(dataSourceurl);
dsc.setDriverName(dataSourcedriver);
dsc.setUsername(dataSourcename);
dsc.setPassword(dataSourcepassword);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setParent(packageParent);
pc.setController("controller"); // 可以不⽤设置,默认是这个
pc.setService("service"); // 同上
pc.setServiceImpl("service.impl"); // 同上
pc.setMapper("dao"); // 默认是mapper
pc.setEntity("entity"); // 默认是entity
pc.setXml("mapping"); // 默认是默认是l
pc.setModuleName("demo"); // 控制层请求地址的包名显⽰
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude(tables.split(",")); // 需要⽣成的表设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名⽣成策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // ⾃动lombok;
strategy.setCapitalMode(false); //【不懂】开启全局⼤写命名
strategy.setSuperMapperClass(null); //【不懂】
/
/ 是否需要开启特定规范字段
if (true == isNormalize) {
strategy.setLogicDeleteFieldName("deleted");
// ⾃动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified",
FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
/
/ 乐观锁
strategy.setVersionFieldName("version");
}
strategy.setRestControllerStyle(true); // 控制:true——⽣成@RsetController false——⽣成@Controller
strategy.setControllerMappingHyphenStyle(true); // 【不知道是啥】
strategy.setEntityTableFieldAnnotationEnable(true); // 表字段注释启动启动模板中的这个 <#vert>
strategy.setEntityBooleanColumnRemoveIsPrefix(true); // 是否删除实体类字段的前缀
strategy.setTablePrefix("mdm_"); // 去掉表名mdm_inf_rec_data中的 mdm_ 类名为InfRecData
strategy.setControllerMappingHyphenStyle(false); // 控制层mapping的映射地址 false:infRecData true:inf_rec_data
mpg.setStrategy(strategy);
//模板⽣成器
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
TemplateConfig tc = new TemplateConfig();
tc.setController("/templatesFreemaker/controller.java");
tc.setService("/templatesFreemaker/service.java");
tc.setServiceImpl("/templatesFreemaker/serviceImpl.java");
tc.setEntity("/templatesFreemaker/entity.java");
tc.setMapper("/templatesFreemaker/mapper.java");
tc.setXml("/l");
mpg.setTemplate(tc);
}
}
在resource下新建⽂件 generate.properties,常⽤的可以放在这⾥
#------------------- 数据源 -------------------#
datasource.username=root
datasource.password=123456
datasource.url=jdbc:mysql://127.0.0.1:3306/basic_project?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 datasource.sql.jdbc.Driver
# ⽗包名
package.atedemo
# 需要⽣成的表名,多张表⽤英⽂逗号隔开 #
datatables.name=user,mdm_inf_rec_data
在springboot项⽬下test下新建 GenerateApplicationTests.java
import batisplus.GenerateMybatisPlus;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.st.context.SpringBootTest;
import st.context.TestPropertySource;
@SpringBootTest
@TestPropertySource("classpath:generate.properties")
class GenerateApplicationTests {
@Value("${datasource.url}")
private String dataSourceurl;
@Value("${datasource.username}")
private String dataSourcename;
@Value("${datasource.password}")
private String dataSourcepassword;
@Value("${datasource.driver-class-name}")
private String dataSourcedriver;
@Value("${datatables.name}")
private String tables;
@Value("${package.parent}")
private String packageParent;
@Value("${datatables.isNormalize}")
private boolean isNormalize;
@Test
void generateMybatisPlusTest() {
new GenerateMybatisPlus().generate(
dataSourceurl,
dataSourcename,
dataSourcepassword,
dataSourcedriver,
tables,
packageParent,
isNormalize);
}
}
最重要的模板内容
controller.java.ftl
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import ditions.query.QueryWrapper;
import atemon.PageResult;
import atemon.Result;
import atemon.StatusCode;
import adata.IPage;
import sion.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
* ${tablement!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@Slf4j
@Api(tags = "${tablement!}")
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMap
pingHyphenStyle??>${controllerMappingHyphen}<#else>${ityPath}</#if>") <#if kotlin>
class ${llerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${llerName} extends ${superControllerClass} {
<#else>
public class ${llerName} {
@Autowired
public ${table.serviceName} ${ityPath}Service;
@ApiOperation(value = "新增")
@PostMapping("/save")
public Result save(@RequestBody ${entity} ${ityPath}){
${ityPath}Service.save(${ityPath});
return new Result(StatusCode.SUCCESS,"保存成功");
}
@ApiOperation(value = "根据id删除")
@PostMapping("/delete/{id}")
public Result delete(@PathVariable("id") Long id){
spring framework表达式assign${veById(id);
return new Result(StatusCode.SUCCESS,"删除成功");
}
@ApiOperation(value = "条件查询")
@PostMapping("/get")
public Result list(@RequestBody ${entity} ${ityPath}){
List<${entity}> ${ityPath}List = ${ityPath}Service.list(new QueryWrapper<>(${ityPath}));
return new Result(StatusCode.SUCCESS,"查询成功",${ityPath}List);
}
@ApiOperation(value = "列表(分页)")
@GetMapping("/list/{pageNum}/{pageSize}")
public Object list(@PathVariable("pageNum")Long pageNum, @PathVariable("pageSize")Long pageSize){
IPage<${entity}> page = ${ityPath}Service.page(
new Page<>(pageNum, pageSize), null);
return new Result(StatusCode.SUCCESS,"查询成功",new PageResult<>(Total(),Records()));
}
@ApiOperation(value = "详情")
@GetMapping("/get/{id}")
public Result get(@PathVariable("id") String id){
${entity} ${ityPath} = ${ById(id);
return new Result(StatusCode.SUCCESS,"查询成功",${ityPath});
}
@ApiOperation(value = "根据id修改")
@PostMapping("/update/{id}")
public Result update(@PathVariable("id") String id, @RequestBody ${entity} ${ityPath}){ ${ityPath}.setId(id);
${ityPath}Service.updateById(${ityPath});
return new Result(StatusCode.SUCCESS,"更新成功");
}
</#if>
}
</#if>
entity.java.ftl
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#vert>
import batisplus.annotation.TableName;
</#if>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
perimental.Accessors;
</#if>
/**
* <p>
* ${tablement!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#vert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value = "${entity}对象", description = "${tablement!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
private static final long serialVersionUID = 1L;
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if fieldment!?length gt 0>
//${fieldment}
<#if swagger2>
@ApiModelProperty(value = "${fieldment}")
<#else>
/**
* ${fieldment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#vert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论