版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1环境
JDK --1.8
maven --3.2.5
IDEA --2008.2
springBoot --2.0.4.RELEASE
2maven依赖
<!--generator--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency>
2.2. 在src/main/resources目录下创建generatorConfig.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>
<!-- 导入配置文件 -->
<properties resource="application.properties"/>
<!-- defaultModelType="flat" 设置复合主键时不单独为主键创建实体 -->
<context id="mysql2Entity" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator type="com.service.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!-- 数据库连接 -->
<jdbcConnection
driverClass="${spring.datasource.driver-class-name}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
<property name="useInformationSchema" value="true"/>
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
<property name="useJSR310Types" value="false"/>
</javaTypeResolver>
<!-- 生成POJO -->
<javaModelGenerator targetPackage="com.spi.pojo"
targetProject="H:\super\super-core\super-core-spi\src\main\java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapper -->
<sqlMapGenerator targetPackage="mapper"
targetProject="H:\super\super-core\super-core-service\src\main\resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成dao接口-->
<javaClientGenerator targetPackage="com.service.dao"
targetProject="H:\super\super-core\super-core-service\src\main\java"
type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<table tableName="plant_quarantine_certification" domainObjectName="PlantQuarantineCertificationPO"
enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
2.3 创建 MyCommentGenerator 类实现 CommentGenerator 从而实现自定义的 pojo、dao 的注释
下面是代码
package com.service;
import com.base.util.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;
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 org.mybatis.generator.internal.util.StringUtility;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author: create by NiceHang
* @version: v1.0.1
* @date:2019/11/27 10:16
*/
public class MyCommentGenerator implements CommentGenerator,Serializable {
private Properties properties = new Properties();
/**
* 抑制日期 默认false:不抑制
*/
private boolean suppressDate = false;
/**
* 抑制注释 默认false:不抑制
*/
private boolean suppressAllComments = false;
/**
* 显示数据库comments 默认false:不显示
*/
private boolean addRemarkComments = false;
/**
* 日期格式
*/
private SimpleDateFormat dateFormat;
public MyCommentGenerator() {
super();
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
}
/**
* 读取配置文件
*
* @param properties
*/
@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
this.suppressDate = StringUtility.isTrue(properties.getProperty("suppressDate"));
this.suppressAllComments = StringUtility.isTrue(properties.getProperty("suppressAllComments"));
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
String dateFormatString = properties.getProperty("dateFormat");
if (StringUtility.stringHasValue(dateFormatString)) {
this.dateFormat = new SimpleDateFormat(dateFormatString);
}
}
/**
* 创建的数据表对应的类添加的注释
*
* /**
* * @author: create by NiceHang
* * @version: v1.0.1
* * @date:2019/11/27 10:16
* *
*
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (!this.suppressAllComments) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * @author create by NiceHang");
topLevelClass.addJavaDocLine(" * @version v1.0.1 ");
topLevelClass.addJavaDocLine(" * @Database table name is " + introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(" * @create " + DateUtils.getCurrDateTimeStr_CN());
topLevelClass.addJavaDocLine(" */");
}
}
/**
* <p>生成xx.java文件(model)属性的注释</p>
*
* @param field
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
if (!this.suppressAllComments) {
// 注释开始的地方
field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
// 开启注释,并且数据库中comment有值
if (this.addRemarkComments && StringUtility.stringHasValue(remarks)) {
// 通过换行符分割 System.getProperty("line.separator"):换行符 ,屏蔽了 Windows和Linux的区别
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
int length = remarkLines.length;
// 如果有多行,就换行显示
for (int i = 0; i < length; i++) {
String remarkLine = remarkLines[i];
field.addJavaDocLine(" * " + remarkLine);
}
}
// 注释结束
field.addJavaDocLine(" */");
}
}
/**
* xxxMapper接口和xxxExample类方法注解
*
* @param method
* @param introspectedTable
*/
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (!this.suppressAllComments) {
method.addJavaDocLine("/**");
// TODO 注释掉搜索名
// method.addJavaDocLine(" * " + method.getName());
List<Parameter> parameters = method.getParameters();
// TODO 入参
parameters.forEach(parameter -> method.addJavaDocLine(" * @param " + parameter.getName()));
// TODO 出参如果有返回类型,添加@return
String returnType = "void";
if (!returnType.equals(method.getReturnType())) {
method.addJavaDocLine(" * @return ");
}
method.addJavaDocLine(" */");
}
}
/**
* 数据库对应实体类的Getter方法注解
*
* @param method
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
/**
* 数据库对应实体类的Setter方法注解
*
* @param method
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
/**
* 生成xxMapper.XML文件的注释
*
* @param xmlElement
*/
@Override
public void addComment(XmlElement xmlElement) {
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
@Override
public void addRootComment(XmlElement rootElement) {
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
}
}
2.4 在generatorConfig.xml--》commentGenerator 标签中需要置换type的指向,指向你自己的 MyCommentGenerator, 使自定义注释生效。
<commentGenerator type="com.service.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
3 创建 Generator 启动类生成代码
package com.service;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author: create by NiceHang
* @version: v1.0.1
* @date:2019/11/27 10:57
*/
public class Generator {
public static void main(String[] args){
try {
List<String> warnings = new ArrayList<>();
String path = null;
path = ResourceUtils.getURL("classpath:generatorConfig.xml").getPath().substring(1);
File configFile = new File(path);
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);
} catch (Exception e) {
//todo
System.out.println(e);
}
}
}