导航栏
实体类中字段注释
package org.mybatis.generator.plugins.comment;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
/**
* 实体类中字段注释
*/
public class CommentGeneratorPlugin implements CommentGenerator {
@Override
public void addConfigurationProperties(Properties properties) {
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
field.addJavaDocLine("/**");
field.addJavaDocLine(" * " + remarks);
field.addJavaDocLine(" */");
field.addJavaDocLine(String.format("@ApiModelProperty(name = \"%s\", value = \"%s\", example = \"\")", introspectedColumn.getJavaProperty(), remarks));
String tableField = Objects.equals("id", field.getName()) ? "@TableId" : "@TableField";
field.addJavaDocLine(tableField + "(\"" + introspectedColumn.getActualColumnName() + "\")");
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
}
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
@Override
public void addComment(XmlElement xmlElement) {
}
@Override
public void addRootComment(XmlElement rootElement) {
}
@Override
public void addClassAnnotation(InnerClass arg0, IntrospectedTable arg1, Set<FullyQualifiedJavaType> arg2) {
}
@Override
public void addFieldAnnotation(Field arg0, IntrospectedTable arg1, Set<FullyQualifiedJavaType> arg2) {
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addGeneralMethodAnnotation(Method arg0, IntrospectedTable arg1, Set<FullyQualifiedJavaType> arg2) {
}
@Override
public void addGeneralMethodAnnotation(Method arg0, IntrospectedTable arg1, IntrospectedColumn arg2, Set<FullyQualifiedJavaType> arg3) {
}
}
实体类注释
package org.mybatis.generator.plugins.field;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.plugins.PublicUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 实体类注释
*/
public class FieldsPlugin extends PluginAdapter {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 导入需要注解的包
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addImportedType("io.swagger.annotations.ApiModel");
topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.TableField");
topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.TableId");
topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.TableName");
topLevelClass.addAnnotation("@Data");
topLevelClass.addAnnotation("@ApiModel(value = \"" + topLevelClass.getType().getShortName() + " Entity\", description = \"" + introspectedTable.getRemarks() + "\")");
topLevelClass.addAnnotation("@TableName(\"" + introspectedTable.getFullyQualifiedTable() + "\")");
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * @ClassName: " + topLevelClass.getType().getShortName() + " Entity");
topLevelClass.addJavaDocLine(" * @Desc: " + introspectedTable.getRemarks());
topLevelClass.addJavaDocLine(" * @Author: xxx");
topLevelClass.addJavaDocLine(" * @Date: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
topLevelClass.addJavaDocLine(" */");
return true;
}
/**
* 不生成getter
*/
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
/**
* 不生成setter
*/
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
@Override
public boolean sqlMapBaseColumnListElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
XmlElement isNullElement = new XmlElement("if"); //$NON-NLS-1$
isNullElement.addAttribute(new Attribute("test", "fields == null")); //$NON-NLS-1$ //$NON-NLS-2$
for (Element e : element.getElements()) {
isNullElement.addElement(e);
}
element.getElements().clear();
element.addElement(isNullElement);
XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$
isNotNullElement.addAttribute(new Attribute("test", "fields != null")); //$NON-NLS-1$ //$NON-NLS-2$
//isNotNullElement.addAttribute(new Attribute("compareValue", "0")); //$NON-NLS-1$ //$NON-NLS-2$
isNotNullElement.addElement(new TextElement("${fields}"));
element.addElement(isNotNullElement);
return super.sqlMapBaseColumnListElementGenerated(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
List<Element> elements = element.getElements();
StringBuilder columns = new StringBuilder();
List<IntrospectedColumn> allColumns = introspectedTable.getAllColumns();
for (IntrospectedColumn introspectedColumn : allColumns) {
columns.append(",").append(introspectedColumn.getActualColumnName());
}
columns.deleteCharAt(0);
elements.set(1, new TextElement(columns.toString()));
return super.sqlMapSelectByPrimaryKeyElementGenerated(element, introspectedTable);
}
/**
* This plugin is always valid - no properties are required
*/
public boolean validate(List<String> warnings) {
return true;
}
}
分页插件
package org.mybatis.generator.plugins.page;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.List;
/**
* 分页插件
*/
public class PaginationPlugin extends PluginAdapter {
@Override
public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// add field, getter, setter for limit clause
addPageNo(topLevelClass, introspectedTable, "pageNo");
addStartRow(topLevelClass, introspectedTable, "startRow");
addPageSize(topLevelClass, introspectedTable, "pageSize");
return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
//XmlElement isParameterPresenteElemen = (XmlElement) element.getElements().get(element.getElements().size() - 1);
XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$
isNotNullElement.addAttribute(new Attribute("test", "startRow != null")); //$NON-NLS-1$ //$NON-NLS-2$
//isNotNullElement.addAttribute(new Attribute("compareValue", "0")); //$NON-NLS-1$ //$NON-NLS-2$
isNotNullElement.addElement(new TextElement("limit #{startRow} , #{pageSize}"));
//isParameterPresenteElemen.addElement(isNotNullElement);
element.addElement(isNotNullElement);
return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}
private void addStartRow(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
CommentGenerator commentGenerator = context.getCommentGenerator();
Field field = new Field();
field.setVisibility(JavaVisibility.PROTECTED);
//field.setType(FullyQualifiedJavaType.getIntInstance());
field.setType(PrimitiveTypeWrapper.getIntegerInstance());
field.setName(name);
//field.setInitializationString("-1");
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setName("set" + camel);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
method.addBodyLine("this." + name + "=" + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(PrimitiveTypeWrapper.getIntegerInstance());
method.setName("get" + camel);
method.addBodyLine("return " + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
}
private void addPageSize(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
CommentGenerator commentGenerator = context.getCommentGenerator();
Field field = new Field();
field.setVisibility(JavaVisibility.PROTECTED);
//field.setType(FullyQualifiedJavaType.getIntInstance());
field.setType(PrimitiveTypeWrapper.getIntegerInstance());
field.setName(name);
field.setInitializationString("10");
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setName("set" + camel);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
method.addBodyLine("this." + name + "=" + name + ";");
//this.startRow = (pageNo-1)*this.pageSize;
method.addBodyLine("this.startRow = (pageNo-1)*this." + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(PrimitiveTypeWrapper.getIntegerInstance());
method.setName("get" + camel);
method.addBodyLine("return " + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
}
private void addPageNo(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) {
CommentGenerator commentGenerator = context.getCommentGenerator();
Field field = new Field();
field.setVisibility(JavaVisibility.PROTECTED);
//field.setType(FullyQualifiedJavaType.getIntInstance());
field.setType(PrimitiveTypeWrapper.getIntegerInstance());
field.setName(name);
field.setInitializationString("1");
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setName("set" + camel);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
method.addBodyLine("this." + name + "=" + name + ";");
method.addBodyLine("this.startRow = (" + name + "-1)*this.pageSize;");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(PrimitiveTypeWrapper.getIntegerInstance());
method.setName("get" + camel);
method.addBodyLine("return " + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
}
/**
* This plugin is always valid - no properties are required
*/
public boolean validate(List<String> warnings) {
return true;
}
}
Controller 扩展方法
1,前面service,serviceImpl,dao都是继承了mybatis-plus提供的基类。
2,controller也可以继承自定义基类,大家根据习惯自由发挥。
3,controller使用的Result返回对象不提供,自己定义。
4,controller使用的SnowflakeIdWorker.Id()不提供,生成主键规则自己定义。
package org.mybatis.generator.plugins.service;
import org.mybatis.generator.api.dom.java.*;
/**
* Controller 扩展方法
*/
public class ControllerExtendPlugin {
private TopLevelClass clazz;
private String modelName;//实体类名
public ControllerExtendPlugin(TopLevelClass clazz, String modelName) {
this.clazz = clazz;
this.modelName = modelName;
}
/**
* 处理
*/
public void handler() {
//删除
createRemoveById();
//添加
createInsert();
//查询详情
createGetById();
//分页查询
createSelectPage();
//修改
createUpdateById();
}
//删除
private void createRemoveById() {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);//修饰符
method.setReturnType(addJavaType("Result"));//返回类型
method.setName("removeById");//方法名
// 添加方法参数
method.addParameter(addParam("@PathVariable String", "id"));
method.addBodyLine("getService().removeById(id);");
method.addBodyLine("return Result.ok(Boolean.TRUE);");//返回
//注解
method.addAnnotation("@DeleteMapping(value = \"/{id}\")");
method.addAnnotation("@ApiOperation(value = \"删除\")");
method.addAnnotation("@ApiImplicitParam(name = \"id\", value = \"主键\", paramType = \"path\", required = true)");
//引用
clazz.addImportedType(addJavaType("com.rma.common.core.model.Result"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.PathVariable"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.DeleteMapping"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiOperation"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiImplicitParam"));
//添加
clazz.addMethod(method);
}
//添加
private void createInsert() {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);//修饰符
method.setReturnType(addJavaType("Result"));//返回类型
method.setName("insertSelective");//方法名
// 添加方法参数
method.addParameter(addParam("@RequestBody T", "insert"));
method.addBodyLine("insert.setId(SnowflakeIdWorker.Id());");
method.addBodyLine("getService().save(insert);");
method.addBodyLine("return Result.ok(Boolean.TRUE);");//返回
//注解
method.addAnnotation("@PutMapping(value = \"\")");
method.addAnnotation("@ApiOperation(value = \"添加\")");
//引用
clazz.addImportedType(addJavaType("com.rma.common.core.model.Result"));
clazz.addImportedType(addJavaType("com.rma.common.core.utils.SnowflakeIdWorker"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.RequestBody"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.PutMapping"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiOperation"));
//添加
clazz.addMethod(method);
}
//查询详情
private void createGetById() {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);//修饰符
method.setReturnType(addJavaType("Result"));//返回类型
method.setName("getById");//方法名
// 添加方法参数
method.addParameter(addParam("@PathVariable String", "id"));
method.addBodyLine("T result = (T) getService().getById(id);");
method.addBodyLine("return Result.ok(result);");//返回
//注解
method.addAnnotation("@GetMapping(value = \"/{id}\")");
method.addAnnotation("@ApiOperation(value = \"查询详情\")");
method.addAnnotation("@ApiImplicitParam(name = \"id\", value = \"主键\", paramType = \"path\", required = true)");
//引用
clazz.addImportedType(addJavaType("com.rma.common.core.model.Result"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.PathVariable"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.GetMapping"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiOperation"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiImplicitParam"));
//添加
clazz.addMethod(method);
}
//分页查询
private void createSelectPage() {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);//修饰符
method.setReturnType(addJavaType("Result<IPage<T>>"));//返回类型
method.setName("selectPage");//方法名
// 添加方法参数
method.addParameter(addParam("@RequestParam(defaultValue = \"1\") Integer", "pageNum"));
method.addParameter(addParam("@RequestParam(defaultValue = \"10\") Integer", "pageSize"));
method.addBodyLine("LambdaQueryWrapper<" + modelName + "> queryWrapper = new LambdaQueryWrapper<>();");
method.addBodyLine("return Result.ok(getService().page(new Page<>(pageNum, pageSize), queryWrapper));");//返回
//注解
method.addAnnotation("@PostMapping(value = \"/page\")");
method.addAnnotation("@ApiOperation(value = \"分页查询\")");
method.addAnnotation("@ApiImplicitParams({\n" +
" @ApiImplicitParam(name = \"pageNum\", value = \"页码\", defaultValue = \"1\", paramType = \"query\"),\n" +
" @ApiImplicitParam(name = \"pageSize\", value = \"每页条数\", defaultValue = \"10\", paramType = \"query\")\n" +
" })");
//引用
clazz.addImportedType(addJavaType("com.rma.common.core.model.Result"));
clazz.addImportedType(addJavaType("com.baomidou.mybatisplus.core.metadata.IPage"));
clazz.addImportedType(addJavaType("com.baomidou.mybatisplus.extension.plugins.pagination.Page"));
clazz.addImportedType(addJavaType("com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.RequestParam"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.PostMapping"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiOperation"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiImplicitParam"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiImplicitParams"));
//添加
clazz.addMethod(method);
}
//修改
private void createUpdateById() {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);//修饰符
method.setReturnType(addJavaType("Result"));//返回类型
method.setName("updateById");//方法名
// 添加方法参数
method.addParameter(addParam("@RequestBody T", "update"));
method.addBodyLine("getService().updateById(update);");
method.addBodyLine("return Result.ok(Boolean.TRUE);");//返回
//注解
method.addAnnotation("@PostMapping(value = \"\")");
method.addAnnotation("@ApiOperation(value = \"修改\")");
//引用
clazz.addImportedType(addJavaType("com.rma.common.core.model.Result"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.RequestBody"));
clazz.addImportedType(addJavaType("org.springframework.web.bind.annotation.RequestBody"));
clazz.addImportedType(addJavaType("io.swagger.annotations.ApiOperation"));
//添加
clazz.addMethod(method);
}
/**
* 添加引用
*/
private FullyQualifiedJavaType addJavaType(String javaType) {
return new FullyQualifiedJavaType(javaType);
}
/**
* 添加方法参数
*/
private Parameter addParam(String javaType, String name) {
return new Parameter(addJavaType(javaType), name, false);
}
}
接口相关类
package org.mybatis.generator.plugins.service;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.plugins.PublicUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
/**
* dao
* service
* serviceImpl
* controller
*/
public class ServiceGeneratorPlugin extends PluginAdapter {
// 项目目录,一般为 .src/main/java
private String targetProject;
// dao包名,如:com.wbr.demo.dao
private String daoPackage;
// service包名,如:com.wbr.demo.service
private String servicePackage;
// service实现类包名,如:com.wbr.demo.service.impl
private String serviceImplPackage;
// Controlle类包名,如:com.wbr.demo.controller
private String controllerPackage;
// service接口名前缀
private String servicePreffix;
// service接口名后缀
private String serviceSuffix;
// service接口的父接口
private String superServiceInterface;
// service实现类的父类
private String superServiceImpl;
// controller类的父类
private String superController;
// dao接口基类
private String superDaoInterface;
private String recordType;
private String modelName;
private FullyQualifiedJavaType model;
private String daoName;
private String serviceName;
private String serviceImplName;
private String controllerName;
@Override
public boolean validate(List<String> warnings) {
boolean valid = true;
targetProject = properties.getProperty("targetProject");
daoPackage = properties.getProperty("daoPackage");
servicePackage = properties.getProperty("servicePackage");
serviceImplPackage = properties.getProperty("serviceImplPackage");
servicePreffix = properties.getProperty("servicePreffix");
servicePreffix = stringHasValue(servicePreffix) ? servicePreffix : "";
serviceSuffix = properties.getProperty("serviceSuffix");
serviceSuffix = stringHasValue(serviceSuffix) ? serviceSuffix : "";
superServiceInterface = properties.getProperty("superServiceInterface");
superServiceImpl = properties.getProperty("superServiceImpl");
superDaoInterface = properties.getProperty("superDaoInterface");
controllerPackage = properties.getProperty("controllerPackage");
superController = properties.getProperty("superController");
return valid;
}
@Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
recordType = introspectedTable.getBaseRecordType();
modelName = recordType.substring(recordType.lastIndexOf(".") + 1);
model = new FullyQualifiedJavaType(recordType);
daoName = daoPackage + "." + modelName + "Dao";
serviceName = servicePackage + "." + servicePreffix + modelName + serviceSuffix;
serviceImplName = serviceImplPackage + "." + modelName + serviceSuffix + "Impl";
controllerName = controllerPackage.concat(".").concat(modelName).concat("Controller");
List<GeneratedJavaFile> answer = new ArrayList<>();
GeneratedJavaFile dao = generateDaoInterface(introspectedTable);
GeneratedJavaFile service = generateServiceInterface(introspectedTable);
GeneratedJavaFile serviceImpl = generateServiceImpl(introspectedTable);
GeneratedJavaFile controller = generateController(introspectedTable);
answer.add(dao);
answer.add(service);
answer.add(serviceImpl);
answer.add(controller);
return answer;
}
// 生成Dao接口
private GeneratedJavaFile generateDaoInterface(IntrospectedTable introspectedTable) {
Interface inf = new Interface(new FullyQualifiedJavaType(daoName));
//添加接口注释,用父类
addJavaDocLine(introspectedTable, inf, "Dao");
inf.setVisibility(JavaVisibility.PUBLIC);
// 添加父接口
if (stringHasValue(superDaoInterface)) {
String superServiceInterfaceName = superDaoInterface.substring(superDaoInterface.lastIndexOf(".") + 1);
inf.addImportedType(new FullyQualifiedJavaType(superDaoInterface));
inf.addImportedType(new FullyQualifiedJavaType(recordType));
inf.addSuperInterface(new FullyQualifiedJavaType(superServiceInterfaceName + "<" + modelName + ">"));
inf.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper"));
inf.addAnnotation("@Mapper");
}
return new GeneratedJavaFile(inf, targetProject, context.getJavaFormatter());
}
// 生成service接口
private GeneratedJavaFile generateServiceInterface(IntrospectedTable introspectedTable) {
Interface inf = new Interface(new FullyQualifiedJavaType(serviceName));
//添加接口注释
addJavaDocLine(introspectedTable, inf, "Service");
inf.setVisibility(JavaVisibility.PUBLIC);
// 添加父接口
if (stringHasValue(superServiceInterface)) {
String superServiceInterfaceName = superServiceInterface.substring(superServiceInterface.lastIndexOf(".") + 1);
inf.addImportedType(new FullyQualifiedJavaType(superServiceInterface));
inf.addImportedType(new FullyQualifiedJavaType(recordType));
inf.addSuperInterface(new FullyQualifiedJavaType(superServiceInterfaceName + "<" + modelName + ">"));
}
return new GeneratedJavaFile(inf, targetProject, context.getJavaFormatter());
}
// 生成serviceImpl实现类
private GeneratedJavaFile generateServiceImpl(IntrospectedTable introspectedTable) {
FullyQualifiedJavaType service = new FullyQualifiedJavaType(serviceName);
FullyQualifiedJavaType serviceImpl = new FullyQualifiedJavaType(serviceImplName);
TopLevelClass clazz = new TopLevelClass(serviceImpl);
//添加类注释
addJavaDocLine(introspectedTable, clazz, "ServiceImpl");
//描述类的作用域修饰符
clazz.setVisibility(JavaVisibility.PUBLIC);
//描述类 引入的类
clazz.addImportedType(service);
//描述类 的实现接口类
clazz.addSuperInterface(service);
if (stringHasValue(superServiceImpl)) {
String superServiceImplName = superServiceImpl.substring(superServiceImpl.lastIndexOf(".") + 1);
clazz.addImportedType(superServiceImpl);
clazz.addImportedType(recordType);
clazz.setSuperClass(superServiceImplName + "<" + modelName + "Dao," + modelName + ">");
clazz.addImportedType(daoName);
}
clazz.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Service"));
clazz.addAnnotation("@Service");
/*String daoFieldType = introspectedTable.getMyBatis3JavaMapperType();
clazz.addImportedType(new FullyQualifiedJavaType(daoFieldType));*/
/*String daoFieldName = firstCharToLowCase(daoFieldType.substring(daoFieldType.lastIndexOf(".") + 1));
//描述类的成员属性
Field daoField = new Field(daoFieldName, new FullyQualifiedJavaType(daoFieldType));
clazz.addImportedType(new FullyQualifiedJavaType("org.springframework.beans.factory.annotation.Autowired"));
//描述成员属性 的注解
daoField.addAnnotation("@Autowired");
//描述成员属性修饰符
daoField.setVisibility(JavaVisibility.PRIVATE);
clazz.addField(daoField);*/
/*//描述 方法名
Method method = new Method("getMapper");
//方法注解
method.addAnnotation("@Override");
FullyQualifiedJavaType methodReturnType = new FullyQualifiedJavaType("Object");
//返回值
method.setReturnType(methodReturnType);
//方法体,逻辑代码
method.addBodyLine("return " + daoFieldName + ";");
//修饰符
method.setVisibility(JavaVisibility.PUBLIC);
clazz.addMethod(method);*/
return new GeneratedJavaFile(clazz, targetProject, context.getJavaFormatter());
}
// 生成controller类
private GeneratedJavaFile generateController(IntrospectedTable introspectedTable) {
FullyQualifiedJavaType controller = new FullyQualifiedJavaType(String.format("%s<T extends %s>", controllerName, modelName));
TopLevelClass clazz = new TopLevelClass(controller);
//添加类注释
addJavaDocLine(introspectedTable, clazz, "Controller");
//描述类的作用域修饰符
clazz.setVisibility(JavaVisibility.PUBLIC);
//引入实体类
clazz.addImportedType(model);
//添加@Slf4j注解,并引入相应的类
clazz.addImportedType(new FullyQualifiedJavaType("lombok.extern.slf4j.Slf4j"));
clazz.addAnnotation("@Slf4j");
//添加@CrossOrigin(maxAge = 3600)注解,并引入相应的类
clazz.addImportedType(new FullyQualifiedJavaType("org.springframework.web.bind.annotation.CrossOrigin"));
clazz.addAnnotation("@CrossOrigin(maxAge = 3600)");
//添加@Controller注解,并引入相应的类
clazz.addImportedType(new FullyQualifiedJavaType("org.springframework.web.bind.annotation.RestController"));
clazz.addAnnotation("@RestController");
//添加@RequestMapping注解,并引入相应的类
clazz.addImportedType(new FullyQualifiedJavaType("org.springframework.web.bind.annotation.RequestMapping"));
String path = introspectedTable.getFullyQualifiedTable().toString().replaceAll("_", "/");
clazz.addAnnotation("@RequestMapping(\"/" + path + "\")");
//添加@Api注解,并引入相应的类
clazz.addImportedType(new FullyQualifiedJavaType("io.swagger.annotations.Api"));
String controllerSimpleName = controllerName.substring(controllerName.lastIndexOf(".") + 1);
clazz.addAnnotation("@Api(tags = \"" + controllerSimpleName + " API\")");
//引入controller的父类和model,并添加泛型
if (stringHasValue(superController)) {
clazz.addImportedType(superController);
clazz.addImportedType(recordType);
FullyQualifiedJavaType superInterfac = new FullyQualifiedJavaType(superController + "<" + modelName + ">");
clazz.addSuperInterface(superInterfac);
}
//引入Service
FullyQualifiedJavaType service = new FullyQualifiedJavaType(serviceName);
clazz.addImportedType(service);
//添加Service成员变量
String serviceFieldName = serviceName.substring(serviceName.lastIndexOf(".") + 1);
Field daoField = new Field(serviceFieldName, new FullyQualifiedJavaType(serviceName));
clazz.addImportedType(new FullyQualifiedJavaType(serviceName));
clazz.addImportedType(new FullyQualifiedJavaType("javax.annotation.Resource"));
//描述成员属性 的注解
daoField.addAnnotation("@Resource");
//描述成员属性修饰符
daoField.setVisibility(JavaVisibility.PRIVATE);
clazz.addField(daoField);
//描述 方法名
Method method = new Method("getService");
//方法注解
FullyQualifiedJavaType methodReturnType = new FullyQualifiedJavaType(serviceName);
//返回类型
method.setReturnType(methodReturnType);
//方法体,逻辑代码
method.addBodyLine("return " + serviceFieldName + ";");
//修饰符
method.setVisibility(JavaVisibility.PUBLIC);
// clazz.addImportedType(superServiceInterface);
clazz.addMethod(method);
//扩展
ControllerExtendPlugin extendMethod = new ControllerExtendPlugin(clazz, modelName);
extendMethod.handler();
return new GeneratedJavaFile(clazz, targetProject, context.getJavaFormatter());
}
/**
* 添加类注释
*/
private void addJavaDocLine(IntrospectedTable introspectedTable, JavaElement clazz, String classNameSuffix) {
clazz.addJavaDocLine("/**");
clazz.addJavaDocLine(String.format(" * @ClassName: %s %s", modelName, classNameSuffix));
clazz.addJavaDocLine(" * @Desc: " + introspectedTable.getRemarks());
clazz.addJavaDocLine(" * @Author: " + PublicUtil.AUTHOR);
clazz.addJavaDocLine(" * @Date: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
clazz.addJavaDocLine(" */");
}
}
执行主类
package org.mybatis.generator.plugins;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.core.io.ClassPathResource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class AppGenerator {
@Test
public void generatorTest() {
try {
// 语料清洗库
generator("rma-gpt-cln", "com.wbr.gpt.cln");
// 视频服务库
generator("rma-gpt-vjs", "com.wbr.gpt.vjs");
} catch (Exception e) {
log.error("err", e);
}
}
/**
* @param xmlName xml文件名
* @param packageName 包路径
*/
private void generator(String xmlName, String packageName) throws Exception {
// 设置系统属性"packageName"为传入的packageName
System.setProperty("packageName", packageName);
// 创建一个空的字符串列表用于存储警告信息
List<String> warnings = new ArrayList<String>();
// 创建一个MyBatisGenerator对象,传入配置解析器、默认的Shell回调和警告列表
MyBatisGenerator generator = new MyBatisGenerator(
new ConfigurationParser(warnings).parseConfiguration(
new ClassPathResource(xmlName + ".xml").getInputStream()),
new DefaultShellCallback(true),
warnings);
// 生成代码
generator.generate(null);
// 打印警告信息
log.info("warnings={}", Arrays.asList(warnings).toString());
// 打印生成成功的信息
log.info("{} ------------ success", xmlName);
}
}
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.maven.idea</groupId>
<artifactId>GeneratorTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>GeneratorTest</name>
<description>反向生成</description>
<properties>
<java.version>1.8</java.version>
<mybatis_generator_core.version>1.3.6</mybatis_generator_core.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis_generator_core.version}</version>
<scope>test</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.4.2</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
</project>
rma-gpt-vjs.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySQL" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<!-- JavaBean 实现 序列化 接口 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<!-- 生成 entity时,生成toString -->
<!--<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>-->
<!-- 自定义物理分页 可生成支持Mysql数据的limit 不支持Oracle -->
<plugin type="org.mybatis.generator.plugins.page.PaginationPlugin"/>
<!-- 自定义查询指定字段 -->
<plugin type="org.mybatis.generator.plugins.field.FieldsPlugin"/>
<!-- 开启支持内存分页 可生成 支持内存分布的方法及参数
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
-->
<!-- generate entity时,生成hashcode和equals方法
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
-->
<!-- 此处是将Example改名为Query 当然 想改成什么都行~ -->
<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
<property name="searchString" value="Example$"/>
<property name="replaceString" value="Query"/>
</plugin>
<plugin type="org.mybatis.generator.plugins.service.ServiceGeneratorPlugin">
<property name="targetProject" value="./src/main/java"/>
<property name="daoPackage" value="${packageName}.dao"/>
<property name="servicePackage" value="${packageName}.service"/>
<property name="serviceImplPackage" value="${packageName}.service.impl"/>
<property name="controllerPackage" value="${packageName}.controller"/>
<!--Dao接口的父接口-->
<property name="superDaoInterface" value="com.baomidou.mybatisplus.core.mapper.BaseMapper"/>
<!--UserService,该值则为Service-->
<property name="serviceSuffix" value="Service"/>
<!--Service接口的父接口-->
<property name="superServiceInterface" value="com.baomidou.mybatisplus.extension.service.IService"/>
<!--ServiceImpl的父类-->
<property name="superServiceImpl" value="com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"/>
<!--controller的父类接口-->
<property name="superController" value=""/>
</plugin>
<commentGenerator type="org.mybatis.generator.plugins.comment.CommentGeneratorPlugin">
<!-- 是否去除自动生成的注释 true:是 : false:否
<property name="suppressAllComments" value="true" />
-->
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/rma-gpt-vjs?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useTimezone=true"
userId="root"
password="root">
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!--默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="${packageName}.entity" targetProject="./src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<!--<sqlMapGenerator targetPackage="${packageName}.mapper" targetProject="./src/main/resources">
<!– enableSubPackages:是否让schema作为包的后缀 –>
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!– targetPackage:mapper接口生成的位置 –>
<javaClientGenerator targetPackage="${packageName}.mapper" targetProject="./src/main/java"
type="XMLMAPPER">
<!– enableSubPackages:是否让schema作为包的后缀 –>
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>-->
<!-- ************************ ****** ************************ -->
<!-- ************************ ****** ************************ -->
<!-- ************************ tables ************************ -->
<!-- ************************ ****** ************************ -->
<!-- <table schema="vjs" tableName="gpt_dict" domainObjectName="GptDict"-->
<!-- enableSelectByExample="false"-->
<!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"></table>-->
<!-- <table schema="vjs" tableName="gpt_dict_detail" domainObjectName="GptDictDetail"-->
<!-- enableSelectByExample="false"-->
<!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"></table>-->
<table schema="vjs" tableName="gpt_%" domainObjectName=""
enableSelectByExample="false"
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"></table>
</context>
</generatorConfiguration>