mybatis-generator自定义注释生成
最近做的项目发现没有中文注释,故查找资料,特此记录。
本文所用的是基于mybatis-generator 1.3.2版本来完成的。
mybatis-generator 自动生成的代码注释是很反人类的,通常我们在使用的时候都是按照如下设置关闭注释:
<commentGenerator>
<!-- 关闭自动生成的注释 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
不过在mybatis-generator官方文档中commentGenerator一节中有这么一段说明:The default implementation is org.mybatis.generator.internal.DefaultCommentGenerator. The default implementation is designed for extensibility if you only want to modify certain behaviors.
既然是可扩展的,那么该如何做呢?文档中也有说明,只需要实现 org.mybatis.generator.api.CommentGenerator接口,同时有一个public的构造函数,然后为commentGenerator添加属性type,并将其值设置为实现类的全路径即可。
1.实现CommentGenerator接口
当然首先你的工程中要有mybatis-generator-core这个jar包.相关pom如下:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<!-- 注意版本.这里我使用的是1.3.2 -->
<version>1.3.2</version>
</dependency>
正文,实现CommentGenerator接口,当然继承默认的实现DefaultCommentGenerator也行.然后实现或者是重写自己需要的方法.过程中最好是参照着DefaultCommentGenerator里面的代码来做.
没什么要多说的,下文是我的实现.
package com.test.util;
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.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties; import static org.mybatis.generator.internal.util.StringUtility.isTrue; /**
* mybatis generator 自定义comment生成器.
* 基于MBG 1.3.2.
*
*/
public class MyCommentGenerator implements CommentGenerator { 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());
} 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.
*/
public void addComment(XmlElement xmlElement) {
return;
} public void addRootComment(XmlElement rootElement) {
// add no document level comments by default
return;
} 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
*/
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
*/
protected String getDateString() {
String result = null;
if (!suppressDate) {
result = currentDateStr;
}
return result;
} 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(" */");
} 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(" */");
} 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(" */");
} 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(" */");
} public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
// method.addJavaDocLine("/**");
// addJavadocTag(method, false);
// method.addJavaDocLine(" */");
} 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(" */");
} 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(" */");
} 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()); sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
sb.append(" ");
sb.append(currentDateStr); // addJavadocTag(innerClass, markAsDoNotDelete); innerClass.addJavaDocLine(" */");
}
}
但是,通过实现CommentGenerator接口的一些不足,毕竟只是实现了CommentGenerator接口,在里面的方法再怎么改,有效的也只是针对model类,并且使用的人大概也发现了,里面的addClassComment方法都知道是在类文件上面生成注释,但是无论我们在这个方法实现里写什么都没有效果,其实因为MGB默认是没有调用这个方法的,这个时候如果有需求希望生成的类文件自动加了类文档说明就办不到了,而如果在源代码的基础上修改,就好办多了,想怎么改就怎么改,只要找对地方,什么样的需要都可以自己写代码来实现.
<?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"> <!-- 配置Run As Maven build : Goals 参数 : mybatis-generator:generate -Dmybatis.generator.overwrite=true -->
<!-- 配置 tableName,使用 Run As Maven build 生成 dao model 层 -->
<generatorConfiguration>
<!-- 配置文件路径 -->
<properties resource="generatorConfig.properties"/> <context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
<property name="javaFileEncoding" value="UTF-8"/> <!-- 生成的pojo,将implements Serializable -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<!-- 这里的type里写的是你的实现类的类全路径 -->
<commentGenerator type="com.test.util.MyCommentGenerator">
</commentGenerator>
<!-- <commentGenerator>
<property name="suppressDate" value="true"/>
<!–关闭注释–>
<property name="suppressAllComments" value="true"/>
</commentGenerator>--> <!--数据库连接信息 -->
<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}"
password="${jdbc.password}">
</jdbcConnection> <!--生成的model 包路径 -->
<javaModelGenerator targetPackage="${model.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="ture"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator> <!--生成xml mapper文件 路径 -->
<sqlMapGenerator targetPackage="${xml.mapper.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator> <!-- 生成的Dao接口 的包路径 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}" targetProject="${target.project}">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator> <!--对应数据库表名 -->
<table tableName="t_user" domainObjectName="User">
<property name="enableCountByExample" value="false"/>
<property name="enableDeleteByExample" value="false"/>
<property name="enableDeleteByPrimaryKey" value="false"/>
<property name="enableInsert" value="false"/>
<property name="enableSelectByPrimaryKey" value="false"/>
<property name="enableUpdateByExample" value="false"/>
<property name="enableUpdateByPrimaryKey" value="false"/>
<property name="selectByExampleQueryId" value="true"/>
<property name="selectByPrimaryKeyQueryId" value="false"/>
<!--自动生成主键,可以代替useGeneratedKeys,大家不用删-->
<generatedKey column="id" sqlStatement="Mysql" type="post" identity="true"/>
</table>
</context>
</generatorConfiguration>
# \u6570\u636E\u5E93\u9A71\u52A8jar \u8DEF\u5F84
drive.class.path=E:\\maven-repository\\reps\\mysql\\mysql-connector-java\\5.1.29\\mysql-connector-java-5.1.29.jar # \u6570\u636E\u5E93\u8FDE\u63A5\u53C2\u6570
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root # \u5305\u8DEF\u5F84\u914D\u7F6E
model.package=com.test.model
dao.package=com.test.dao
xml.mapper.package=com.test.dao
target.project=src/main/java
2.使用Java方式运行MBG
package com.test.util; import org.mybatis.generator.api.MyBatisGenerator;
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.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* 描述:使用Java方式运行MBG
*
*
*/
public class GeneratorStartUp {
public static void main(String[] args) throws URISyntaxException {
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("generatorConfig-Java.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
} catch (XMLParserException e) {
e.printStackTrace();
}
}
}
mybatis-generator自定义注释生成的更多相关文章
- MyBatis Generator 自定义生成注释
注释生成器 为了生成db里面的注释,必须自定义注释生成器 EmptyCommentGenerator: import org.mybatis.generator.api.CommentGenerato ...
- Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
自己手动实现的前提,对maven项目有基本的了解,在本地成功搭建了maven环境,可以参考我之前的文章:maven环境搭建 项目里新建表时model,mapper以及mapper.xml基本都是用My ...
- mybatis generator 使用教程(生成带注释的实体类)
引言: 最近的一个项目,由于数据库表巨多,导致需要创建N多个java实体.dao.mapper.xml映射文件,如果均使用纯手工编写,无疑需要耗费大量时间和精力.于是上网学习了mybatis gene ...
- 关于 mybatis-generator自定义注释生成 使用DefaultCommentGenerator重写来完成
项目里新建表时model,mapper以及mapper.xml基本都是用Mybatis Generator(以下简称为MBG)自动生成的,但是MBG自动生成的model的注释实在有点非人类,至少中国人 ...
- Eclipse 使用mybatis generator插件自动生成代码
Eclipse 使用mybatis generator插件自动生成代码 标签: mybatis 2016-12-07 15:10 5247人阅读 评论(0) 收藏 举报 .embody{ paddin ...
- Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
在看本篇之前,最好先看一下上一篇通过实现CommentGenerator接口的方法来实现中文注释的例子,因为很多操作和上一篇基本是一致的,所以本篇可能不那么详细. 首先说一下上篇通过实现Comment ...
- 记一次 IDEA mybatis.generator 自定义扩展插件
在使用 idea mybatis.generator 生成的代码,遇到 生成的代码很多重复的地方, 虽然代码是生成的,我们也不应该允许重复的代码出现,因为这些代码后期都要来手动维护. 对于生成时间戳注 ...
- Mybatis Generator代码自动生成(实体类、dao层、映射文件)
写了一段时间增删改查有点厌烦,自己找了下网上的例子鼓捣了下自动生成. 首先得有一个配置文件: generatorConfig.xml <?xml version="1.0" ...
- 使用eclipse插件mybatis generator来自动生成实体类及映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...
随机推荐
- JavaScript工作机制:V8 引擎内部机制及如何编写优化代码的5个诀窍
概述 JavaScript引擎是一个执行JavaScript代码的程序或解释器.JavaScript引擎可以被实现为标准解释器,或者实现为以某种形式将JavaScript编译为字节码的即时编译器. 下 ...
- IT人们给个建议
开篇声明:我本身是中学老师,师范类大学计算机专业毕业,现在马上研究生学位就要拿上了,平时在学校搞网络维护什么的,事少,业余时间充足,也不想拘泥于做老师拿点工资,觉得白学计算机了,所以也搞些业余开发,如 ...
- 高通Vuforia
这里使用高通的Vuroria来做一个AR歌姬. 工具: Vuforia,MMD4Mecanim 模型: 初音未来pmd模型文件,极乐净土vmd动作文件. 逻辑: 当发现识别卡时:开启音乐,模型速度为1 ...
- Codeforces Round #460 (Div. 2)
A. Supermarket We often go to supermarkets to buy some fruits or vegetables, and on the tag there pr ...
- 【bzoj2563】 阿狸和桃子的游戏
题目 非常妙的题目,一看到就以为是一道博弈,之后就不会做了 正解非常巧妙,由于我们只需要求出最后两个人得分的差值,所以对于每一条边我们将其的权值拆成两边,分给其连接的两个点 如果这两个点被同一个人选择 ...
- [学习笔记] numpy次成分分析和PCA降维
存个代码,以后参考. numpy次成分分析和PCA降维 SVD分解做次成分分析 原图: 次成分复原图: 代码: import numpy as np from numpy import linalg ...
- luogu P2124 奶牛美容
嘟嘟嘟 首先数据范围那么小,那么算法也是相当暴力的. 对于一个点(x, y)所属的联通块,预处理出从这个点出发到这个块外的所有点的曼哈顿距离.复杂度O(n4). 然后求答案:最少答案不一定是三个联通块 ...
- 【转】Android应用程序窗口(Activity)窗口对象(Window)创建指南
在前文中,我们分析了Android应用程序窗口的运行上下文环境的创建过程.由此可知,每一个Activity组件都有一个关联的ContextImpl对象,同时,它还关联有一个Window对象,用来描述一 ...
- 【转】有关onpropertychange事件
<div style="border:1px solid #fc0;height:24px;width:300px;" id="target">&l ...
- BP神经网络—java实现(转载)
神经网络的结构 神经网络的网络结构由输入层,隐含层,输出层组成.隐含层的个数+输出层的个数=神经网络的层数,也就是说神经网络的层数不包括输入层.下面是一个三层的神经网络,包含了两层隐含层,一个输出层. ...