Mybatis Generator 自定義註釋
1.mybatis generator使用
1.1. 閱讀官網文檔 ,導入maven plugin
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
</dependencies>
</plugin>
1.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>
<context id="MysqlTables" targetRuntime="MyBatis3">
<!--解決讀取數據庫中的comments中文亂碼-->
<property name="javaFileEncoding" value="UTF-8"/>
<!--分頁-->
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
<!--註釋:課可通過type自動配置-->
<commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--jdbcConnection: 數據庫連接的屬性-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/blog_community?serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--javaModelGenerator: Java模型生成器的屬性 此元素是<context>元素的必需子元素。-->
<!--enableSubPackages: value爲true時,包不存在會自動創建-->
<javaModelGenerator targetPackage="cn.edu.nwafu.ssr.community.model" targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--Mapper.xml生成-->
<sqlMapGenerator targetPackage="cn.edu.nwafu.ssr.community.xml" targetProject="src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--XXXMapper.java生成-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.nwafu.ssr.community.mapper"
targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- useActualColumnNames:如果爲true,則MBG將使用從數據庫元數據返回的列名作爲生成的域對象的屬性。
如果爲false(默認),則MBG將嘗試以駝峯式表示返回的名稱。
默認值爲false。-->
<table schema="DB2ADMIN" tableName="tb_user" domainObjectName="User">
<!--<property name="useActualColumnNames" value="true"/>-->
</table>
</context>
</generatorConfiguration>
1.3. 使用一下命令運行創建
mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate
注意:使用的mysql驅動如果很新,需要在url中加入?serverTimezone=UTC,即
<!--jdbcConnection: 數據庫連接的屬性-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/blog_community?serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
否則會執行不了,會ERROR
[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project blog_community: The
server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (
via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
1.4. 在springboot啓動類 XXXApplication中添加註解
@MapperScan(basePackages = "test.dao") //包爲mapper所在的包
1.5. 上邊@MapperScan註解,只是讓springboot知道了Mapper.java文件的位置,但是不知道Mapper.xml文件的位置,此時需要在application.properties文件中配置
##mybatis配置
##mybatis.mapper-locations:mapper.xml文件的位置
##mybatis.type-aliases-package:實體類所在的包
mybatis.mapper-locations=classpath*:/test/**/*Mapper.xml
mybatis.type-aliases-package=test.model
1.6. 官方文檔
1.6.1. mybatis generator
1.6.2. spring-boot-starter
1.7.可實現CommentGenerator 類,從而自動配置添加的註釋
1.7.1. 實現CommentGenerator 類
package cn.edu.nwafu.ssr.community;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author shensr
* @version V1.0
* @description mybatis generator自定義生成註釋插件類
* @create 2019/10/4
**/
public class MyCommentGenerator implements CommentGenerator {
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);
}
}
/**
* 日期格式化
*
* @return 格式化後的日期
*/
protected String getDateString() {
if (this.suppressDate) {
return null;
} else {
return this.dateFormat != null ? this.dateFormat.format(new Date()) : (new Date()).toString();
}
}
/**
* 創建的數據表對應的類添加的註釋
*
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (!this.suppressAllComments) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * @author shensr");
topLevelClass.addJavaDocLine(" * @version V1.0 ");
topLevelClass.addJavaDocLine(" * @description MyBatis Generator 自動創建,對應數據表爲:" + introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(" * @create " + this.getDateString());
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("/**");
method.addJavaDocLine(" * " + method.getName());
List<Parameter> parameters = method.getParameters();
parameters.forEach(parameter -> method.addJavaDocLine(" * @param " + parameter.getName()));
// 如果有返回類型,添加@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) {
}
}
1.7.2.在generatorConfig.xml配飾文件中添加
<!--註釋:課可通過type自動配置-->
<commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
1.7.3. 通過java方式啓動mbg ,maven會出現一些問題
package cn.edu.nwafu.ssr.community;
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 java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author shensr
* @version V1.0
* @description 通過java方式啓動mbg,實現自定配置註解,使用maven方式會出現問題
* @create 2019/10/9
**/
public class Generator {
public static void main(String[] args) {
List<String> warnings = new ArrayList<>();
// 覆蓋
boolean overwrite = true;
// 給出generatorConfig.xml文件的位置
File configFile = new File("D:\\IdeaProjects\\blog_community\\src\\main\\resources\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
try {
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.7.8. 生成效果
package cn.edu.nwafu.ssr.community.model;
/**
* @author shensr
* @version V1.0
* @description MyBatis Generator 自動創建,對應數據表爲:tb_user
* @create 2019/10/09
*/
public class User {
/**
* ID
*/
private Integer id;
/**
* 賬戶Id
*/
private String accountId;
/**
* 用戶名
*/
private String name;
/**
* token
*/
private String token;
/**
* 創建時間
*/
private Long gmtCreate;
/**
* 更新時間
*/
private Long gmtModified;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId == null ? null : accountId.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token == null ? null : token.trim();
}
public Long getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Long gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Long getGmtModified() {
return gmtModified;
}
public void setGmtModified(Long gmtModified) {
this.gmtModified = gmtModified;
}
}