您的位置:首页 > 其它

mybatis-generator自定义注释生成

2017-12-14 11:44 471 查看
最近做的项目发现没有中文注释,故查找资料,特此记录。

本文所用的是基于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
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: