Mybatis Generator 自定義注釋
1.mybatis generator使用
1.1. 閱讀官網(wǎng)文檔 ,導(dǎo)入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目錄下創(chuàng)建generatorConfig.xml配置文件
文件模板在官網(wǎng)有提供
<?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">
<!--解決讀取數(shù)據(jù)庫(kù)中的comments中文亂碼-->
<property name="javaFileEncoding" value="UTF-8"/>
<!--分頁(yè)-->
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
<!--注釋:課可通過type自動(dòng)配置-->
<commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--jdbcConnection: 數(shù)據(jù)庫(kù)連接的屬性-->
<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時(shí),包不存在會(huì)自動(dòng)創(chuàng)建-->
<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將使用從數(shù)據(jù)庫(kù)元數(shù)據(jù)返回的列名作為生成的域?qū)ο蟮膶傩浴? 如果為false(默認(rèn)),則MBG將嘗試以駝峰式表示返回的名稱。
默認(rèn)值為false。-->
<table schema="DB2ADMIN" tableName="tb_user" domainObjectName="User">
<!--<property name="useActualColumnNames" value="true"/>-->
</table>
</context>
</generatorConfiguration>
1.3. 使用一下命令運(yùn)行創(chuàng)建
mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate
注意:使用的mysql驅(qū)動(dòng)如果很新,需要在url中加入?serverTimezone=UTC,即
<!--jdbcConnection: 數(shù)據(jù)庫(kù)連接的屬性-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/blog_community?serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
否則會(huì)執(zhí)行不了,會(huì)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啟動(dòng)類 XXXApplication中添加注解
@MapperScan(basePackages = "test.dao") //包為mapper所在的包
1.5. 上邊@MapperScan注解,只是讓springboot知道了Mapper.java文件的位置,但是不知道Mapper.xml文件的位置,此時(shí)需要在application.properties文件中配置
##mybatis配置
##mybatis.mapper-locations:mapper.xml文件的位置
##mybatis.type-aliases-package:實(shí)體類所在的包
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.可實(shí)現(xiàn)CommentGenerator 類,從而自動(dòng)配置添加的注釋
1.7.1. 實(shí)現(xiàn)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();
/**
* 抑制日期 默認(rèn)false:不抑制
*/
private boolean suppressDate = false;
/**
* 抑制注釋 默認(rèn)false:不抑制
*/
private boolean suppressAllComments = false;
/**
* 顯示數(shù)據(jù)庫(kù)comments 默認(rèn)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();
}
}
/**
* 創(chuàng)建的數(shù)據(jù)表對(duì)應(yīng)的類添加的注釋
*
* @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 自動(dòng)創(chuàng)建,對(duì)應(yīng)數(shù)據(jù)表為:" + 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();
// 開啟注釋,并且數(shù)據(jù)庫(kù)中comment有值
if (this.addRemarkComments && StringUtility.stringHasValue(remarks)) {
// 通過換行符分割 System.getProperty("line.separator"):換行符 ,屏蔽了 Windows和Linux的區(qū)別
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);
}
}
// 注釋結(jié)束
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(" */");
}
}
/**
* 數(shù)據(jù)庫(kù)對(duì)應(yīng)實(shí)體類的Getter方法注解
*
* @param method
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
/**
* 數(shù)據(jù)庫(kù)對(duì)應(yīng)實(shí)體類的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自動(dòng)配置-->
<commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
<property name="addRemarkComments" value="true"/>
</commentGenerator>
1.7.3. 通過java方式啟動(dòng)mbg ,maven會(huì)出現(xiàn)一些問題
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方式啟動(dòng)mbg,實(shí)現(xiàn)自定配置注解,使用maven方式會(huì)出現(xiàn)問題
* @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 自動(dòng)創(chuàng)建,對(duì)應(yīng)數(shù)據(jù)表為:tb_user
* @create 2019/10/09
*/
public class User {
/**
* ID
*/
private Integer id;
/**
* 賬戶Id
*/
private String accountId;
/**
* 用戶名
*/
private String name;
/**
* token
*/
private String token;
/**
* 創(chuàng)建時(shí)間
*/
private Long gmtCreate;
/**
* 更新時(shí)間
*/
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;
}
}