mybatis-generator自定义注释生成

Posted esther-qing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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里面的代码来做.

没什么要多说的,下文是我的实现.

技术分享图片
  1 package com.test.util;
  2 import org.mybatis.generator.api.CommentGenerator;
  3 import org.mybatis.generator.api.IntrospectedColumn;
  4 import org.mybatis.generator.api.IntrospectedTable;
  5 import org.mybatis.generator.api.dom.java.*;
  6 import org.mybatis.generator.api.dom.xml.XmlElement;
  7 import org.mybatis.generator.config.MergeConstants;
  8 import org.mybatis.generator.config.PropertyRegistry;
  9 
 10 import java.text.SimpleDateFormat;
 11 import java.util.Date;
 12 import java.util.Properties;
 13 
 14 import static org.mybatis.generator.internal.util.StringUtility.isTrue;
 15 
 16 /**
 17  * mybatis generator 自定义comment生成器.
 18  * 基于MBG 1.3.2. 
 19  *
 20  */
 21 public class MyCommentGenerator implements CommentGenerator {
 22 
 23     private Properties properties;
 24     private Properties systemPro;
 25     private boolean suppressDate;
 26     private boolean suppressAllComments;
 27     private String currentDateStr;
 28 
 29     public MyCommentGenerator() {
 30         super();
 31         properties = new Properties();
 32         systemPro = System.getProperties();
 33         suppressDate = false;
 34         suppressAllComments = false;
 35         currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
 36     }
 37 
 38     public void addJavaFileComment(CompilationUnit compilationUnit) {
 39         // add no file level comments by default
 40         return;
 41     }
 42 
 43     /**
 44      * Adds a suitable comment to warn users that the element was generated, and
 45      * when it was generated.
 46      */
 47     public void addComment(XmlElement xmlElement) {
 48         return;
 49     }
 50 
 51     public void addRootComment(XmlElement rootElement) {
 52         // add no document level comments by default
 53         return;
 54     }
 55 
 56     public void addConfigurationProperties(Properties properties) {
 57         this.properties.putAll(properties);
 58 
 59         suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
 60 
 61         suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
 62     }
 63 
 64     /**
 65      * This method adds the custom javadoc tag for. You may do nothing if you do
 66      * not wish to include the Javadoc tag - however, if you do not include the
 67      * Javadoc tag then the Java merge capability of the eclipse plugin will
 68      * break.
 69      *
 70      * @param javaElement the java element
 71      */
 72     protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
 73         javaElement.addJavaDocLine(" *");
 74         StringBuilder sb = new StringBuilder();
 75         sb.append(" * ");
 76         sb.append(MergeConstants.NEW_ELEMENT_TAG);
 77         if (markAsDoNotDelete) {
 78             sb.append(" do_not_delete_during_merge");
 79         }
 80         String s = getDateString();
 81         if (s != null) {
 82             sb.append(‘ ‘);
 83             sb.append(s);
 84         }
 85         javaElement.addJavaDocLine(sb.toString());
 86     }
 87 
 88     /**
 89      * This method returns a formated date string to include in the Javadoc tag
 90      * and XML comments. You may return null if you do not want the date in
 91      * these documentation elements.
 92      *
 93      * @return a string representing the current timestamp, or null
 94      */
 95     protected String getDateString() {
 96         String result = null;
 97         if (!suppressDate) {
 98             result = currentDateStr;
 99         }
100         return result;
101     }
102 
103     public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
104         if (suppressAllComments) {
105             return;
106         }
107         StringBuilder sb = new StringBuilder();
108         innerClass.addJavaDocLine("/**");
109         sb.append(" * ");
110         sb.append(introspectedTable.getFullyQualifiedTable());
111         sb.append(" ");
112         sb.append(getDateString());
113         innerClass.addJavaDocLine(sb.toString());
114         innerClass.addJavaDocLine(" */");
115     }
116 
117     public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
118         if (suppressAllComments) {
119             return;
120         }
121 
122         StringBuilder sb = new StringBuilder();
123 
124         innerEnum.addJavaDocLine("/**");
125         //      addJavadocTag(innerEnum, false);
126         sb.append(" * ");
127         sb.append(introspectedTable.getFullyQualifiedTable());
128         innerEnum.addJavaDocLine(sb.toString());
129         innerEnum.addJavaDocLine(" */");
130     }
131 
132     public void addFieldComment(Field field, IntrospectedTable introspectedTable,
133                                 IntrospectedColumn introspectedColumn) {
134         if (suppressAllComments) {
135             return;
136         }
137 
138         StringBuilder sb = new StringBuilder();
139 
140         field.addJavaDocLine("/**");
141         sb.append(" * ");
142         sb.append(introspectedColumn.getRemarks());
143         field.addJavaDocLine(sb.toString());
144 
145         //      addJavadocTag(field, false);
146 
147         field.addJavaDocLine(" */");
148     }
149 
150     public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
151         if (suppressAllComments) {
152             return;
153         }
154 
155         StringBuilder sb = new StringBuilder();
156 
157         field.addJavaDocLine("/**");
158         sb.append(" * ");
159         sb.append(introspectedTable.getFullyQualifiedTable());
160         field.addJavaDocLine(sb.toString());
161         field.addJavaDocLine(" */");
162     }
163 
164     public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
165         if (suppressAllComments) {
166             return;
167         }
168         //      method.addJavaDocLine("/**");
169         //      addJavadocTag(method, false);
170         //      method.addJavaDocLine(" */");
171     }
172 
173     public void addGetterComment(Method method, IntrospectedTable introspectedTable,
174                                  IntrospectedColumn introspectedColumn) {
175         if (suppressAllComments) {
176             return;
177         }
178 
179         method.addJavaDocLine("/**");
180 
181         StringBuilder sb = new StringBuilder();
182         sb.append(" * 获取");
183         sb.append(introspectedColumn.getRemarks());
184         method.addJavaDocLine(sb.toString());
185 
186         sb.setLength(0);
187         sb.append(" * @return ");
188         sb.append(introspectedColumn.getActualColumnName());
189         sb.append(" ");
190         sb.append(introspectedColumn.getRemarks());
191         method.addJavaDocLine(sb.toString());
192 
193         //      addJavadocTag(method, false);
194 
195         method.addJavaDocLine(" */");
196     }
197 
198     public void addSetterComment(Method method, IntrospectedTable introspectedTable,
199                                  IntrospectedColumn introspectedColumn) {
200         if (suppressAllComments) {
201             return;
202         }
203 
204 
205         method.addJavaDocLine("/**");
206         StringBuilder sb = new StringBuilder();
207         sb.append(" * 设置");
208         sb.append(introspectedColumn.getRemarks());
209         method.addJavaDocLine(sb.toString());
210 
211         Parameter parm = method.getParameters().get(0);
212         sb.setLength(0);
213         sb.append(" * @param ");
214         sb.append(parm.getName());
215         sb.append(" ");
216         sb.append(introspectedColumn.getRemarks());
217         method.addJavaDocLine(sb.toString());
218 
219         //      addJavadocTag(method, false);
220 
221         method.addJavaDocLine(" */");
222     }
223 
224     public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
225         if (suppressAllComments) {
226             return;
227         }
228 
229         StringBuilder sb = new StringBuilder();
230 
231         innerClass.addJavaDocLine("/**");
232         sb.append(" * ");
233         sb.append(introspectedTable.getFullyQualifiedTable());
234         innerClass.addJavaDocLine(sb.toString());
235 
236         sb.setLength(0);
237         sb.append(" * @author ");
238         sb.append(systemPro.getProperty("user.name"));
239         sb.append(" ");
240         sb.append(currentDateStr);
241 
242         //      addJavadocTag(innerClass, markAsDoNotDelete);
243 
244         innerClass.addJavaDocLine(" */");
245     }
246 }
View Code

但是,通过实现CommentGenerator接口的一些不足,毕竟只是实现了CommentGenerator接口,在里面的方法再怎么改,有效的也只是针对model类,并且使用的人大概也发现了,里面的addClassComment方法都知道是在类文件上面生成注释,但是无论我们在这个方法实现里写什么都没有效果,其实因为MGB默认是没有调用这个方法的,这个时候如果有需求希望生成的类文件自动加了类文档说明就办不到了,而如果在源代码的基础上修改,就好办多了,想怎么改就怎么改,只要找对地方,什么样的需要都可以自己写代码来实现.

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 
 6 <!-- 配置Run As Maven build : Goals 参数 : mybatis-generator:generate -Dmybatis.generator.overwrite=true -->
 7 <!-- 配置 tableName,使用 Run As Maven build 生成 dao model 层 -->
 8 <generatorConfiguration>
 9     <!-- 配置文件路径 -->
10     <properties resource="generatorConfig.properties"/>
11 
12     <context id="DB2Tables" targetRuntime="MyBatis3">
13         <!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
14         <property name="javaFileEncoding" value="UTF-8"/>
15 
16         <!-- 生成的pojo,将implements Serializable -->
17         <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
18         <!-- 这里的type里写的是你的实现类的类全路径 -->
19         <commentGenerator type="com.test.util.MyCommentGenerator">
20         </commentGenerator>
21      <!--   <commentGenerator>
22             <property name="suppressDate" value="true"/>
23             &lt;!&ndash;关闭注释&ndash;&gt;
24             <property name="suppressAllComments" value="true"/>
25         </commentGenerator>-->
26 
27         <!--数据库连接信息 -->
28         <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}"
29                         password="${jdbc.password}">
30         </jdbcConnection>
31 
32         <!--生成的model 包路径 -->
33        <javaModelGenerator targetPackage="${model.package}" targetProject="${target.project}">
34             <property name="enableSubPackages" value="ture"/>
35             <property name="trimStrings" value="true"/>
36         </javaModelGenerator>
37 
38         <!--生成xml mapper文件 路径 -->
39         <sqlMapGenerator targetPackage="${xml.mapper.package}" targetProject="${target.project}">
40             <property name="enableSubPackages" value="true"/>
41         </sqlMapGenerator>
42 
43         <!-- 生成的Dao接口 的包路径 -->
44         <javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}" targetProject="${target.project}">
45             <property name="enableSubPackages" value="true"/>
46         </javaClientGenerator>
47 
48         <!--对应数据库表名 -->
49         <table tableName="t_user" domainObjectName="User">
50             <property name="enableCountByExample" value="false"/>
51             <property name="enableDeleteByExample" value="false"/>
52             <property name="enableDeleteByPrimaryKey" value="false"/>
53             <property name="enableInsert" value="false"/>
54             <property name="enableSelectByPrimaryKey" value="false"/>
55             <property name="enableUpdateByExample" value="false"/>
56             <property name="enableUpdateByPrimaryKey" value="false"/>
57             <property name="selectByExampleQueryId" value="true"/>
58             <property name="selectByPrimaryKeyQueryId" value="false"/>
59             <!--自动生成主键,可以代替useGeneratedKeys,大家不用删-->
60             <generatedKey column="id" sqlStatement="mysql" type="post" identity="true"/>
61         </table>
62     </context>
63 </generatorConfiguration>
View Code
技术分享图片
# \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
View Code

2.使用Java方式运行MBG

技术分享图片
 1 package com.test.util;
 2 
 3 import org.mybatis.generator.api.MyBatisGenerator;
 4 import org.mybatis.generator.config.Configuration;
 5 import org.mybatis.generator.config.xml.ConfigurationParser;
 6 import org.mybatis.generator.exception.InvalidConfigurationException;
 7 import org.mybatis.generator.exception.XMLParserException;
 8 import org.mybatis.generator.internal.DefaultShellCallback;
 9 
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.net.URISyntaxException;
13 import java.sql.SQLException;
14 import java.util.ArrayList;
15 import java.util.List;
16 
17 /**
18  * 描述:使用Java方式运行MBG
19  *
20  * 
21  */
22 public class GeneratorStartUp {
23     public static void main(String[] args) throws URISyntaxException {
24         try {
25             List<String> warnings = new ArrayList<String>();
26             boolean overwrite = true;
27             ClassLoader classloader = Thread.currentThread().getContextClassLoader();
28             InputStream is = classloader.getResourceAsStream("generatorConfig-Java.xml");
29             ConfigurationParser cp = new ConfigurationParser(warnings);
30             Configuration config = cp.parseConfiguration(is);
31             DefaultShellCallback callback = new DefaultShellCallback(overwrite);
32             MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
33             myBatisGenerator.generate(null);
34         } catch (SQLException e) {
35             e.printStackTrace();
36         } catch (IOException e) {
37             e.printStackTrace();
38         } catch (InterruptedException e) {
39             e.printStackTrace();
40         } catch (InvalidConfigurationException e) {
41             e.printStackTrace();
42         } catch (XMLParserException e) {
43             e.printStackTrace();
44         }
45     }
46 }
View Code

 

以上是关于mybatis-generator自定义注释生成的主要内容,如果未能解决你的问题,请参考以下文章

代码演示Mybatis-Generator 扩展自定义生成

mybatis-generator

mybatis-generator扩展

SSM开发 | 开发自定义插件,使 mybatis-generator 支持软删除

Android Studio自定义注释模板及生成JavaDoc

mybatis-generator 生成代码字段名默认按驼峰命名,可否设置