1、maven引入 mybatis-plus-generator 和模板引擎,你也可以使用freemarker之类的,看个人
com.baomidou
mybatis-plus-generator
3.5.1
org.apache.velocity
velocity-engine-core
2.0
2、创建MybatisCrud工具类,这里可以做很多个性化配置,比如改名他默认的 IService之类的,指定表,忽略某些字段等。更多详情见官网 代码生成器配置新 | MyBatis-Plus
package com.XXXX.utils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.XXXX.entity.BaseEntity;
import java.util.Collections;
/**
* @Auther:Tiancong Zou
* @Date: 2023/3/16 21:46
* @Description:
*/
public class MybatisCrud {
public static void main(String[] args) {
FastAutoGenerator.create(
"jdbc:mysql://127.0.0.1:3306/数据库名" ,
"root" ,
"")
.globalConfig(builder -> {
builder.author("Tiancong Zou") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D:\\myJavaTest\\"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.XXXX") // 设置父包名
.mapper("dao")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\myJavaTest\\mapper\\")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.convertServiceFileName((entityName -> entityName + "Service"));
builder.addInclude("sys_dict_item");// 设置需要生成的表名
builder.entityBuilder()
.superClass(BaseEntity.class )
.addIgnoreColumns("deleted","create_date","update_date");
})
.execute();
}
}
3、copy模板,进行定制配置,找到jar包下的模板,复制templates到resources文件夹下,删除其他你不需要的模板。
4、模板配置,这边使用 velocity 模板做演示
4.1 controller.java.vm
package ${package.Controller};
import org.springframework.web.bind.annotation.*;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.muchuantong.utils.Result;
import com.muchuantong.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
*
* $!{table.comment} 前端控制器
*
*
* @Author: ${author}
* @Date: ${date}
* @Annotation:
*/
@RestController
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
public class ${table.controllerName} {
@Autowired
private ${table.serviceName} ${table.entityPath}Service;
// 分页
@GetMapping("getPage")
public Result
4.2 service.java.vm
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.muchuantong.utils.Result;
import java.util.Map;
/**
*
* $!{table.comment} 服务类
*
*
* @Author: ${author}
* @Date: ${date}
* @Annotation:
*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
Result getPage(DTO dto);
}
4.3 serviceImpl.java.vm
package ${package.ServiceImpl};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.primitives.Longs;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import com.muchuantong.utils.Result;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Optional;
/**
*
* $!{table.comment} 服务实现类
*
*
* @Author: ${author}
* @Date: ${date}
* @Annotation:
*/
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Override
public Result getPage(DTO dto){
QueryWrapper<${entity}> wrapper=new QueryWrapper<>();
Page<${entity}> page=page(new Page<>(dto.getCurrent(),dto.getSize()),wrapper);
return new Result<> (page);
}
}
4.4 entity.java.vm
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
/**
*
* $!{table.comment}
*
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Getter
@Setter
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${swagger})
@ApiModel(value = "${entity}对象", description = "$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#elseif(${entitySerialVersionUID})
public class ${entity} implements Serializable {
#else
public class ${entity}{
#end
#if(${entitySerialVersionUID})
private static final long serialVersionUID = 1L;
#end
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
#if(${swagger})
@ApiModelProperty("${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${field.versionField})
@Version
#end
## 逻辑删除注解
#if(${field.logicDeleteField})
@TableLogic
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------
#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
#if(${chainModel})
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(${activeRecord})
@Override
public Serializable pkVal() {
#if(${keyPropertyName})
return this.${keyPropertyName};
#else
return null;
#end
}
#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}
4.5 mapper.java.vm
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
#if(${mapperAnnotation})
import org.apache.ibatis.annotations.Mapper;
#end
/**
*
* $!{table.comment} Mapper 接口
*
*
* @Author: ${author}
* @Date: ${date}
* @Annotation:
*/
#if(${mapperAnnotation})
@Mapper
#end
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
#end
4.6 mapper.xml.vm
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
#end
#end
#foreach($field in ${table.commonFields})
${field.columnName},
#end
${table.fieldNames}
5、生成代码预览,毫无问题 controller
package com.muchuantong.controller;
import com.muchuantong.entity.DTO;
import org.springframework.web.bind.annotation.*;
import com.muchuantong.service.SysDictItemService;
import com.muchuantong.entity.SysDictItem;
import com.muchuantong.utils.Result;
import com.muchuantong.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
*
* 前端控制器
*
*
* @Author: Tiancong Zou
* @Date: 2023-03-28
* @Annotation:
*/
@RestController
@RequestMapping("/sysDictItem")
public class SysDictItemController {
@Autowired
private SysDictItemService sysDictItemService;
// 分页
@GetMapping("getPage")
public Result page(@RequestBody DTO dto){
return sysDictItemService.getPage(dto);
}
// 新增
@PostMapping("save")
public Result save(@RequestBody SysDictItem sysDictItem){
sysDictItem.setId(Long.toString(SnowFlake.nextId()));
sysDictItem.setCreateDate(new Timestamp(new Date().getTime()));
sysDictItem.setUpdateDate(new Timestamp(new Date().getTime()));
try{
sysDictItemService.save(sysDictItem);
return new Result<>();
}catch(Exception e){
e.printStackTrace();
return new Result<>("201" ,"未知错误");
}
}
// 修改
@PostMapping("update")
public Result update(@RequestBody SysDictItem sysDictItem){
try{
sysDictItem.setUpdateDate(new Timestamp(new Date().getTime()));
sysDictItemService.updateById(sysDictItem);
return new Result<>();
}catch(Exception e){
e.printStackTrace();
return new Result<>("201" ,"未知错误");
}
}
// 根据id获取
@GetMapping("getById/{id}")
public Result getById(@PathVariable("id") Long id){
SysDictItem sysDictItem = sysDictItemService.getById(id);
return new Result<>(sysDictItem);
}
// 逻辑删除
@PostMapping("deleteByIds")
public Result deleteByIds(@RequestBody List ids){
for (Long id : ids) {
SysDictItem sysDictItem = sysDictItemService.getById(id);
sysDictItem.setDeleted(1);
try {
sysDictItemService.updateById(sysDictItem);
return new Result<>();
} catch (Exception e) {
e.printStackTrace();
return new Result<>("201", "未知错误");
}
}
return null;
}
}