mybatis-generator是一个很好的数据库逆向生成Java实体的插件,但不能添加中文注释和注解,如果我们想生成下面这样一个实体类,那么就只能自己动手扩展一下mybatis-generator
generatorConfig.xml 配置如下:
自定义的实体注释:
package util;
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 org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
/**
* mybatis generator 自定义comment生成器. 字段注释内容
* 基于MBG 1.3.2.
*/
public class MyCommentGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;
public MyCommentGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
// add no file level comments by default
return;
}
/**
* Adds a suitable comment to warn users that the element was generated, and
* when it was generated.
*/
@Override
public void addComment(XmlElement xmlElement) {
return;
}
@Override
public void addRootComment(XmlElement rootElement) {
// add no document level comments by default
return;
}
@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
}
/**
* This method adds the custom javadoc tag for. You may do nothing if you do
* not wish to include the Javadoc tag - however, if you do not include the
* Javadoc tag then the Java merge capability of the eclipse plugin will
* break.
*
* @param javaElement the java element
*/
@Override
protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
javaElement.addJavaDocLine(" *");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(MergeConstants.NEW_ELEMENT_TAG);
if (markAsDoNotDelete) {
sb.append(" do_not_delete_during_merge");
}
String s = getDateString();
if (s != null) {
sb.append(' ');
sb.append(s);
}
javaElement.addJavaDocLine(sb.toString());
}
/**
* This method returns a formated date string to include in the Javadoc tag
* and XML comments. You may return null if you do not want the date in
* these documentation elements.
*
* @return a string representing the current timestamp, or null
*/
@Override
protected String getDateString() {
String result = null;
if (!suppressDate) {
result = currentDateStr;
}
return result;
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append(" ");
sb.append(getDateString());
innerClass.addJavaDocLine(sb.toString());
innerClass.addJavaDocLine(" */");
}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine("/**");
// addJavadocTag(innerEnum, false);
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerEnum.addJavaDocLine(sb.toString());
innerEnum.addJavaDocLine(" */");
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
field.addJavaDocLine(sb.toString());
// addJavadocTag(field, false);
field.addJavaDocLine(" */");
// field.addAnnotation("@Size(min = 0, max = " +
// introspectedColumn.getLength() + " , message =
// \"长度必须在{min}和{max}之间\")");
// field.addAnnotation("@NotNull"); if
// (introspectedColumn.isStringColumn()) {
// topLevelClass.addImportedType("javax.validation.constraints.Size");
// field.addAnnotation("@Size(min = 0, max = " +
// introspectedColumn.getLength() + " , message =
// \"长度必须在{min}和{max}之间\")"); }
List primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
for (IntrospectedColumn col : primaryKeyColumns) {
if (col.getActualColumnName().equals(introspectedColumn.getActualColumnName())) {
field.addAnnotation("@Id");
}
}
/*
除开id的其他字段上生成@Column注解
field.addAnnotation("@Column(name = \"" + introspectedColumn.getActualColumnName() + "\")");*/
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
field.addJavaDocLine(sb.toString());
field.addJavaDocLine(" */");
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
// method.addJavaDocLine("/**");
// addJavadocTag(method, false);
// method.addJavaDocLine(" */");
}
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
sb.setLength(0);
sb.append(" * @return ");
sb.append(introspectedColumn.getActualColumnName());
sb.append(" ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
// addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
Parameter parm = method.getParameters().get(0);
sb.setLength(0);
sb.append(" * @param ");
sb.append(parm.getName());
sb.append(" ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
// addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
topLevelClass.addImportedType("javax.persistence.Column");
topLevelClass.addImportedType("javax.persistence.Id");
topLevelClass.addImportedType("javax.persistence.Table");
topLevelClass.addImportedType("org.apache.ibatis.type.Alias");
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
topLevelClass.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(sb.toString());
sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
sb.append(" ");
sb.append(currentDateStr);
// addJavadocTag(innerClass, markAsDoNotDelete);
topLevelClass.addJavaDocLine(" */");
topLevelClass.addAnnotation("@Table(name = \"" + introspectedTable.getFullyQualifiedTable() + "\")");
}
// 首字母转小写
public static String toLowerCaseFirstOne(String s) {
if (Character.isLowerCase(s.charAt(0))) {
return s;
} else {
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
Set imports) {
System.out.println(method.getName());
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn, Set imports) {
System.out.println(method.getName());
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
Set imports) {
System.out.println(field.getName());
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn, Set imports) {
System.out.println(field.getName());
field.addAnnotation("@Column(name = \"" + field.getName() + "\")");
}
@Override
public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable,
Set imports) {
System.out.println(innerClass);
}
}
自定义的toString方法:
package util;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.util.List;
/**
* mybatis generator 自定义toString插件
* 基于MBG 1.3.2
*/
public class MyToStringPlugin extends PluginAdapter {
public MyToStringPlugin() {
}
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.generateToString(introspectedTable, topLevelClass);
return true;
}
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.generateToString(introspectedTable, topLevelClass);
return true;
}
@Override
public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
this.generateToString(introspectedTable, topLevelClass);
return true;
}
private void generateToString(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(FullyQualifiedJavaType.getStringInstance());
method.setName("toString");
if (introspectedTable.isJava5Targeted()) {
method.addAnnotation("@Override");
}
//添加方法注释
this.context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
//下面两句method.addBodyLine使用其中之一即可
//使用自定义toString工具类
//method.addBodyLine("return ToStringUtils.toSimpleString(this);");
//使用commons-lang3的工具类
//添加包
topLevelClass.addImportedType("org.apache.commons.lang3.builder.ToStringBuilder");
topLevelClass.addImportedType("org.apache.commons.lang3.builder.ToStringStyle");
method.addBodyLine("return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);");
//添加方法
topLevelClass.addMethod(method);
}
/*
private void generateToString(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(FullyQualifiedJavaType.getStringInstance());
method.setName("toString");
if (introspectedTable.isJava5Targeted()) {
method.addAnnotation("@Override");
}
this.context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
method.addBodyLine("StringBuilder sb = new StringBuilder();");
method.addBodyLine("sb.append(getClass().getSimpleName());");
method.addBodyLine("sb.append(\" [\");");
StringBuilder sb = new StringBuilder();
Iterator i$ = topLevelClass.getFields().iterator();
while(i$.hasNext()) {
Field field = (Field)i$.next();
String property = field.getName();
sb.setLength(0);
sb.append("sb.append(\"").append(", ").append(property).append("=\")").append(".append(").append(property).append(");");
method.addBodyLine(sb.toString());
}
method.addBodyLine("sb.append(\"]\");");
method.addBodyLine("return sb.toString();");
topLevelClass.addMethod(method);
}
*/
@Override
public boolean validate(List warnings) {
return true;
}
}
配置文件主要配置连接数据库的必需参数以及一些路径:
#Mybatis Generator configuration
#java的目录路径
target.project=src/main/java
#resources的目录路径
target.resources=src/main/resources
#生成实体类地址
model.target.package=com.yixunlian.pojo
#生成mapper(xml)地址
mapper.target.package=com.yixunlian.mapper.xml
#生成dao接口(mapper)地址
dao.target.package=com.yixunlian.mapper
#自定义comment生成器地址
my.commentGenerator.address=util.MyCommentGenerator
#自定义toString插件地址
my.toStringPlugin.address=util.MyToStringPlugin
#自定义toString插件地址
my.baseMapperGeneratorPlugin.address=util.BaseMapperGeneratorPlugin
#数据库信息
#需要指明mysql数据库连接器的绝对路径,比较麻烦。只是可选项。所以不写也可以
#jdbc.driverLocation=D:\gitresource\mysql\mysql-connector-java\5.1.45\mysql-connector-java-5.1.45.jar
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/yixunlian
jdbc_user=root
jdbc_password=root
通过代码的方式运行:
package util;
import org.mybatis.generator.api.ShellRunner;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 逆向工程生成器
* Created by yixunlian
*/
public class MyBatisGenerator {
//根据配置文件,生成相应的model实体类,mapper接口,mapperXMl文件
public static void main(String[] args) {
/*第一种方式:
try {
List warnings = new ArrayList();
boolean overwrite = true;
//注意:使用绝对路径 请根据自己本机的具体路径重新配置 否则运行不成功
File configFile = new File("C:\\Users\\yuanyuana\\Desktop\\易迅连\\逆向工程\\mybatis-generator\\src\\main\\resources\\mybatis-generator\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
org.mybatis.generator.api.MyBatisGenerator myBatisGenerator = new org.mybatis.generator.api.MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}*/
//第二种方式(我喜欢下面的这种,更简洁):
args = new String[]{"-configfile", "src\\main\\resources\\mybatis-generator\\generatorConfig.xml", "-overwrite"};
ShellRunner.main(args);
}
}
实体类要继承的基础类basePojo
package com.pojo;
import java.io.Serializable;
import java.util.Date;
public abstract class BasePojo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private Date created;
private Date updated;
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
项目依赖pom.xml:
4.0.0
mybatisgenerator
mybatis-generator
0.0.1-SNAPSHOT
jar
mybatis-generator
mybatis-逆向工程
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
UTF-8
UTF-8
1.8
3.3.2
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.generator
mybatis-generator
1.3.7
org.mybatis.generator
mybatis-generator-core
1.3.7
jar
org.apache.commons
commons-lang3
${commons-lang3.version}
com.github.pagehelper
pagehelper
3.7.5
com.github.jsqlparser
jsqlparser
0.9.1
com.github.abel533
mapper
2.3.4
maven-war-plugin
maven-compiler-plugin
1.8
mapper文件:
实体类结构:
自定义的toString方法:
代码链接:代码链接
参考链接:https://my.oschina.net/wangmengjun/blog/784697