mybatis-generator自定義註釋生成

最近作的項目發現沒有中文註釋,故查找資料,特此記錄。html

本文所用的是基於mybatis-generator 1.3.2版本來完成的。java

mybatis-generator 自動生成的代碼註釋是很反人類的,一般咱們在使用的時候都是按照以下設置關閉註釋:mysql

<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.sql

既然是可擴展的,那麼該如何作呢?文檔中也有說明,只須要實現 org.mybatis.generator.api.CommentGenerator接口,同時有一個public的構造函數,而後爲commentGenerator添加屬性type,並將其值設置爲實現類的全路徑便可。數據庫

1.實現CommentGenerator接口

固然首先你的工程中要有mybatis-generator-core這個jar包.相關pom以下:api

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <!-- 注意版本.這裏我使用的是1.3.2 -->
    <version>1.3.2</version>
</dependency>

正文,實現CommentGenerator接口,固然繼承默認的實現DefaultCommentGenerator也行.而後實現或者是重寫本身須要的方法.過程當中最好是參照着DefaultCommentGenerator裏面的代碼來作.mybatis

沒什麼要多說的,下文是個人實現.app

  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默認是沒有調用這個方法的,這個時候若是有需求但願生成的類文件自動加了類文檔說明就辦不到了,而若是在源代碼的基礎上修改,就好辦多了,想怎麼改就怎麼改,只要找對地方,什麼樣的須要均可以本身寫代碼來實現.dom

 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方式運行MBGeclipse

 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
相關文章
相關標籤/搜索