需求:
controller 生成基本的CRUD方法
entity在日前字段上添加@JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss")的注解,同时添加lombok的基本注解
将controller.java.vm entity.java.vm 模板放到项目/src/main/resources/templates 目录下
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
/**
* mybatis代码生成器
*/
@Slf4j
public class MpGenerator3 {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/bimstudy-web/src/test/java");//生成文件的输出目录
gc.setAuthor("caobin");//开发人员
gc.setOpen(true);//是否打开输出目录
gc.setServiceName("I%sService");//service 命名方式
gc.setServiceImplName("%sServiceImpl");//service impl 命名方式
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setSwagger2(true);
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://mysql:3306/bimstudy?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public"); 数据库 schema name
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));//父包模块名
pc.setParent("com.bimstudy");//父包名。// 自定义包路径 如果为空,将下面子包名必须写全部, 否则就只需写子包名
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");//设置控制器包名
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>();
map.put("currentTimeMillis", System.currentTimeMillis() & 0x0000000000ffffff);
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/permission.sql.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/bimstudy-web/src/test/resources/sql/"
+ "/" + tableInfo.getEntityName() + ".sql";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig());
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");//自定义继承的Entity类全称,带包名
strategy.setEntityLombokModel(true);//【实体】是否为lombok模型(默认 false)
strategy.setEntityBuilderModel(true);
strategy.setRestControllerStyle(true);//生成 @RestController 控制器
//strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");//自定义继承的Controller类全称,带包名
strategy.setInclude("tb_cb","tb_user");//需要包含的表名,允许正则表达式
//strategy.setSuperEntityColumns("id");//自定义基础的Entity类,公共字段
strategy.setControllerMappingHyphenStyle(true);//驼峰转连字符
strategy.setTablePrefix("tb_");//表前缀
ArrayList<TableFill> tableFills = Lists.newArrayList(
new TableFill("create_time", FieldFill.INSERT),
new TableFill("create_user_id", FieldFill.INSERT),
new TableFill("update_time", FieldFill.UPDATE),
new TableFill("update_user_id", FieldFill.UPDATE)
);
strategy.setTableFillList(tableFills);
mpg.setStrategy(strategy);
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
package ${package.Controller};
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bimstudy.annotation.AccessLimit;
import com.bimstudy.annotation.CurrentUser;
import com.bimstudy.annotation.ValidationParam;
import com.bimstudy.base.PublicResultConstant;
import com.bimstudy.config.ResponseHelper;
import com.bimstudy.config.ResponseModel;
import com.bimstudy.entity.User;
import com.bimstudy.service.IUserService;
import com.bimstudy.util.ComUtil;
import com.bimstudy.annotation.Log;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.time.LocalDateTime;
import io.swagger.annotations.Api;
import ${package.Entity}.${entity};
import ${package.Service}.I${entity}Service;
#if(${superControllerClassPackage})
${superControllerClassPackage}
;
#end
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.lang.Assert;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@Slf4j
@Api(description = "$!{table.comment}" )
@RequestMapping("/${table.entityPath}")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
@Autowired
private ${table.serviceName} ${table.entityPath}Service;
/**
* 根据ID查找数据
*/
@ApiOperation(value = "根据ID查找数据")
@Log(action="findById",modelName= "${table.controllerName}",description="根据ID查找数据")
@RequiresPermissions("${table.entityPath}:find")
@GetMapping("/findById")
public ResponseModel<${entity}> findById(@RequestParam Long id){
${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);
//Assert.notNull(${table.entityPath},"未查询到此ID");
return ResponseHelper.succeed(${table.entityPath});
}
/**
* 获取数据列表
*/
@ApiOperation(value = "获取数据列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageIndex", value = "第几页" , dataType = "int",paramType="query"),
@ApiImplicitParam(name = "pageSize", value = "每页多少条" , dataType = "int",paramType="query")
})
@Log(action="findByPage",modelName= "${table.controllerName}",description="获取数据列表")
@RequiresPermissions("${table.entityPath}:find")
@GetMapping("/findByPage")
public ResponseModel<IPage<${entity}>> findByPage(
@RequestParam(name = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
@RequestParam(name = "pageSize", defaultValue = "20", required = false) Integer pageSize){
return ResponseHelper.succeed(${table.entityPath}Service.page(new Page<>(pageIndex, pageSize),new QueryWrapper<>()));
}
/**
* 获取所有记录
*/
@ApiOperation(value = "获取所有记录")
@Log(action="findAll",modelName= "${table.controllerName}",description="获取所有记录")
@RequiresPermissions("${table.entityPath}:find")
@GetMapping("/findAll")
public ResponseModel<List<${entity}>> findAll(){
return ResponseHelper.succeed(${table.entityPath}Service.list(new QueryWrapper<${entity}>()));
}
/**
* 添加
* @param ${table.entityPath}
* @return
*/
@ApiOperation(value = "添加")
@Log(action="add",modelName= "${table.controllerName}",description="添加")
@RequiresPermissions("${table.entityPath}:add")
@PostMapping("/add")
public ResponseModel add(@RequestBody ${entity} ${table.entityPath}) throws Exception{
return ResponseHelper.succeed(${table.entityPath}Service.save(${table.entityPath}));
}
/**
* 根据id删除
* @param id ID
* @return success/false
*/
@ApiOperation(value = "根据id删除")
@Log(action="deleteById",modelName= "${table.controllerName}",description="根据id删除")
@RequiresPermissions("${table.entityPath}:delete")
@PostMapping("/deleteById")
public ResponseModel deleteById(@RequestParam Long id) {
${entity} ${table.entityPath} = new ${entity}();
${table.entityPath}.setId(id);
return ResponseHelper.succeed(${table.entityPath}Service.removeById(${table.entityPath}));
}
/**
* 批量删除
* @param ids ids
* @return success/false
*/
@ApiOperation(value = "批量删除")
@Log(action="deleteBatch",modelName= "${table.controllerName}",description="批量删除")
@RequiresPermissions("${table.entityPath}:delete")
@PostMapping("/deleteBatch")
public ResponseModel deleteBatch(@RequestBody List<Long> ids) {
return ResponseHelper.succeed(${table.entityPath}Service.removeByIds(ids));
}
/**
* 编辑
* @param ${table.entityPath} 实体
* @return success/false
*/
@ApiOperation(value = "编辑")
@Log(action="update",modelName= "${table.controllerName}",description="编辑")
@RequiresPermissions("${table.entityPath}:update")
@PostMapping("/update")
public ResponseModel update(@RequestBody ${entity} ${table.entityPath}) {
${table.entityPath}.setUpdateTime(LocalDateTime.now());
return ResponseHelper.succeed(${table.entityPath}Service.updateById(${table.entityPath}));
}
}
#end
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.*;
import lombok.experimental.Accessors;
#end
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.alibaba.fastjson.annotation.JSONField;
/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${swagger2})
@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}> {
#else
public class ${entity} implements Serializable {
#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(${swagger2})
@ApiModelProperty(value = "${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
@Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
@TableLogic
#end
## JsonFormat注解
#if(${field.propertyType.equals("LocalDate")})
@JSONField(format = "yyyy-MM-dd")
#end
#if(${field.propertyType.equals("LocalDateTime")})
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
#end
###if(${field.propertyName.equals("updateTime")} || ${field.propertyName.equals("updateUserId")})
## @TableField( fill = FieldFill.UPDATE)
###end
###if(${field.propertyName.equals("createTime")} || ${field.propertyName.equals("createUserId")})
## @TableField( fill = FieldFill.INSERT)
###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(${entityBuilderModel})
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(${entityBuilderModel})
return this;
#end
}
#end
#end
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(${activeRecord})
@Override
protected 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
}
#set($roleId='role-cf8fea2055344df59a0d3e80540c78f9')
#set($id1=$cfg.currentTimeMillis - 1)
#set($id2=$cfg.currentTimeMillis - 2)
#set($id3=$cfg.currentTimeMillis - 3)
#set($id4=$cfg.currentTimeMillis - 4)
#set($id5=$cfg.currentTimeMillis - 5)
delete from `tb_role_to_menu` where role_to_menu_id in ('${id1}','${id2}','${id3}','${id4}','${id5}');
INSERT INTO `tb_role_to_menu` VALUES ('${id1}', '${roleId}', '${id1}');
INSERT INTO `tb_role_to_menu` VALUES ('${id2}', '${roleId}', '${id2}');
INSERT INTO `tb_role_to_menu` VALUES ('${id3}', '${roleId}', '${id3}');
INSERT INTO `tb_role_to_menu` VALUES ('${id4}', '${roleId}', '${id4}');
INSERT INTO `tb_role_to_menu` VALUES ('${id5}', '${roleId}', '${id5}');
delete from `tb_menu` where menu_code in ('${id1}','${id2}','${id3}','${id4}','${id5}');
INSERT INTO `tb_menu` VALUES ('${id1}', '0', '${id1}', '${table.entityPath}', '$!{table.comment}', '1', '1', '', '1.jpg');
INSERT INTO `tb_menu` VALUES ('${id2}', '${id1}', '${id2}', '${table.entityPath}:find', '查找', '2', '2', '/${table.entityPath}/findByPage', '1.jpg');
INSERT INTO `tb_menu` VALUES ('${id3}', '${id1}', '${id3}', '${table.entityPath}:add', '添加', '2', '3', '/${table.entityPath}/add', '1.jpg');
INSERT INTO `tb_menu` VALUES ('${id4}', '${id1}', '${id4}', '${table.entityPath}:delete', '删除', '2', '4', '/${table.entityPath}/delete', '1.jpg');
INSERT INTO `tb_menu` VALUES ('${id5}', '${id1}', '${id5}', '${table.entityPath}:update', '修改', '2', '5', '/${table.entityPath}/update', '1.jpg');