<dependencies>
<!-- mybatis相关依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 自动生成代码相关依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
package com.yun.mybatis.generator;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
/**
* @author hyun
* @date 2020/6/25
*/
public class MyGenerator implements CommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String nowTime;
public MyGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
nowTime = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
}
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
String author = properties.getProperty("author");
String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
// 获取表注释
String remarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + remarks);
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date()));
topLevelClass.addJavaDocLine(" */");
}
/**
* 类的注释
* @param innerClass
* @param introspectedTable
* @param markAsDoNotDelete
*/
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
sb.append(" ");
sb.append(nowTime);
innerClass.addJavaDocLine(" */");
}
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().replace("\n", " "));
innerClass.addJavaDocLine(" */");
}
/**
* 设置字段注释
*/
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().replace("\n", " "));
field.addJavaDocLine(" */");
}
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().replace("\n", " "));
field.addJavaDocLine(" */");
}
/**
* 设置setter方法注释
*/
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().replace("\n", " "));
// sb.setLength(0);
// sb.append(" * @author ");
// sb.append(systemPro.getProperty("user.name"));
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// sb.setLength(0);
// if(suppressDate){
// sb.append(" * @date " + nowTime);
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// sb.setLength(0);
// }
// Parameter parm = method.getParameters().get(0);
// sb.append(" * @param ");
// sb.append(parm.getName());
// sb.append(" ");
// sb.append(introspectedColumn.getRemarks());
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// method.addJavaDocLine(" */");
}
/**
* 设置getter方法注释
*/
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().replace("\n", " "));
// sb.setLength(0);
// sb.append(" * @author ");
// sb.append(systemPro.getProperty("user.name"));
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// sb.setLength(0);
// if(suppressDate){
// sb.append(" * @date " + nowTime);
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// sb.setLength(0);
// }
// sb.append(" * @return ");
// sb.append(introspectedColumn.getActualColumnName());
// sb.append(" ");
// sb.append(introspectedColumn.getRemarks());
// method.addJavaDocLine(sb.toString().replace("\n", " "));
// method.addJavaDocLine(" */");
}
public void addJavaFileComment(CompilationUnit compilationUnit) {
if (suppressAllComments) {
return;
}
return;
}
public void addComment(XmlElement xmlElement) {
return;
}
public void addRootComment(XmlElement rootElement) {
return;
}
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = Boolean.valueOf(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = Boolean.valueOf(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
}
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());
}
protected String getDateString() {
String result = null;
if (!suppressDate) {
result = nowTime;
}
return result;
}
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
innerEnum.addJavaDocLine(" */");
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
Set<FullyQualifiedJavaType> imports) {
// TODO Auto-generated method stub
}
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
// TODO Auto-generated method stub
}
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
Set<FullyQualifiedJavaType> imports) {
// TODO Auto-generated method stub
}
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
// TODO Auto-generated method stub
}
public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable,
Set<FullyQualifiedJavaType> imports) {
// TODO Auto-generated method stub
}
public static void main( String[] args ) throws Exception {
List<String> warnings = new ArrayList();
File configFile = new File("F:/workplace/hyunmybatis/src/main/resources/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
<?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>
<!-- 引入配置文件 -->
<properties resource="db.properties" />
<!-- 加载数据库驱动 -->
<!-- <classPathEntry location="${class_path}" /> -->
<!-- context:生成一组对象的环境
id:必选,上下文id,用于在生成错误时提示
defaultModelType:指定生成对象的样式
1,conditional:类似hierarchical;
2,flat:所有内容(主键,blob)等全部生成在一个对象中,推荐使用;
3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class)
targetRuntime:
1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
-->
<context id="context1" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<commentGenerator type="com.yun.mybatis.generator.MyGenerator">
<property name="author" value="hyun"/>
<property name="dateFormat" value="yyyy/MM/dd"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<!-- <property name="suppressAllComments" value="true" /> -->
<!-- 阻止注释中包含时间戳 true:是 : false:否 -->
<property name="suppressDate" value="true" />
<!-- 注释是否包含数据库表的注释信息 true:是 : false:否 -->
<!-- <property name="addRemarkComments" value="true" /> -->
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="${jdbc_driver}"
connectionURL="${jdbc_url}" userId="${jdbc_username}" password="${jdbc_password}" >
<property name="useInformationSchema" value="true" />
</jdbcConnection>
<!-- java模型创建器,是必须要的元素 负责:1,key类(见context的defaultModelType);2,java类;3,查询类
targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;
targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
-->
<javaModelGenerator targetPackage="com.yun.mybatis.entity" targetProject="${project_src}">
<!-- 设置一个根对象,
如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类;在Table的rootClass属性中可以覆盖该选项
注意:如果在key class或者record class中有root class相同的属性,MBG就不会重新生成这些属性了,包括:
1,属性名相同,类型相同,有相同的getter/setter方法;
-->
<!--<property name="rootClass" value="com.yun.mybatis.entity.BaseEntity" />-->
</javaModelGenerator>
<!-- 生成SQL map的XML文件生成器,
targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;
targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
-->
<sqlMapGenerator targetPackage="." targetProject="${project_mapper_xml}">
</sqlMapGenerator>
<!-- 对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口
type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
-->
<javaClientGenerator targetPackage="com.yun.mybatis.mapper" targetProject="${project_src}" type="XMLMAPPER" />
<!-- shema 数据库 tableName表明 -->
<!-- <table schema="${jdbc_username}" tableName="%" >
<generatedKey column="id" sqlStatement="MySql"/>
</table> -->
<table schema="${jdbc_username}" tableName="account" >
<generatedKey column="id" sqlStatement="MySql"/>
</table>
<table schema="${jdbc_username}" tableName="role" >
<generatedKey column="id" sqlStatement="MySql"/>
</table>
</context>
</generatorConfiguration>
db.properties配置文件:
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/tzpt?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
jdbc_username=root
jdbc_password=123456
project_src =src/main/java
project_mapper_xml =src/main/resources/sqlmapper
#class_path=E:/repo/mysql/mysql-connector-java/5.1.18/mysql-connector-java-5.1.18.jar