把Mybatis Generator生成的代码加上想要的注释
作者:王建乐
1 前言
在日常开发工作中,我们经常用Mybatis Generator根据表结构生成对应的实体类和Mapper文件。但是Mybatis Generator默认生成的代码中,注释并不是我们想要的,所以一般在Generator配置文件中,会设置不自动生成注释。带来的问题就是自动生成代码之后,我们还要自己去类文件中把注释加上,如果生成的类较少还好,如果有生成很多类文件,自己加注释是一件繁琐的工作。
通过重写Mybatis Generator的CommentGenerator接口,可以方便地生成自己想要的注释,减少重复工作。
2 使用Java方式执行Mybatis Generator
2.1 IDEA中新建Maven项目
pom.xml中引入jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyGenerator</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
</project>
2.2 创建generatorConfig.xml
随便找个目录放,我放在src/main/resources目录下
<?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="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >
<!-- 生成的 Java 文件的编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 格式化 Java 代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化 XML 代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<commentGenerator>
<property name="suppressAllComments" value="false" />
</commentGenerator>
<!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="URL"
userId="user" password="password">
<!-- 设置 useInformationSchema 属性为 true -->
<property name="useInformationSchema" value="true" />
</jdbcConnection>
<!-- 生成实体的位置 -->
<javaModelGenerator targetPackage="com.jd.bulk"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaModelGenerator>
<!-- 生成 Mapper XML 的位置 -->
<sqlMapGenerator targetPackage="com.jd.bulk"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成 Mapper 接口的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.jd.bulk"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 设置数据库的表名和实体类名 -->
<table tableName="worker" domainObjectName="Worker"/>
</context>
</generatorConfiguration>
2.3 创建main方法,运行Generator
public class Generator {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<>(2);
ConfigurationParser cp = new ConfigurationParser(warnings);
File configFile = new File("src/main/resources/generatorConfig.xml");
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
运行main方法,生成默认注释如下,并不是我们想要的注释,所以一般会配置为注释不生成:

2.4 实现CommentGenerator接口
重写以下方法,自定义注释
public class MySQLCommentGenerator implements CommentGenerator {
private final Properties properties;
public MySQLCommentGenerator() {
properties = new Properties();
}
@Override
public void addConfigurationProperties(Properties properties) {
// 获取自定义的 properties
this.properties.putAll(properties);
}
/**
* 重写给实体类加的注释
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
String author = properties.getProperty("author");
String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
// 获取表注释
String remarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + remarks);
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date()));
topLevelClass.addJavaDocLine(" */");
}
/**
* 重写给实体类字段加的注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
// 获取列注释
String remarks = introspectedColumn.getRemarks();
field.addJavaDocLine("/**");
field.addJavaDocLine(" * " + remarks);
field.addJavaDocLine(" */");
}
/**
* 重写给实体类get方法加的注释
*/
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
// 获取表注释
String remarks = introspectedColumn.getRemarks();
method.addJavaDocLine("/**");
method.addJavaDocLine(" * " + method.getName());
method.addJavaDocLine(" */");
}
2.5 修改generatorConfig.xml配置
将generatorConfig.xml文件中的commentGenerator做如下修改,type属性选择自己的实现类
<commentGenerator type="com.generator.MySQLCommentGenerator">
<property name="author" value="Your Name"/>
<property name="dateFormat" value="yyyy/MM/dd"/>
</commentGenerator>
运行main方法,生成注释如下:

3 使用Maven方式执行Mybatis Generator
Pom.xml文件中增加以下配置,需要引入generator插件时,依赖实现CommentGenerator接口的jar包,要先把自己的jar包install到本地仓库。
否则会报com.generator.MySQLCommentGenerator找不到,其他配置同上。
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<!-- 其他的数据库,需要修改依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 引用实现CommentGenerator接口的jar包 -->
<dependency>
<groupId>org.example</groupId>
<artifactId>MyGenerator</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</plugins>
4 源码分析
查看执行Mybatis Generator的main方法,主要分为两部分,解析指定的配置文件与调用生成java文件和Mapper文件的方法

4.1 解析指定的xml配置文件
跟踪解析xml文件的方法cp.parseConfiguration(configFile)发现,底层以Document形式读取xml文件,根据标签名解析各标签属性,保存到Configuration实例中。

其中解析commentGenerator标签的方法parseCommentGenerator(context, childNode)中,会获取commentGenerator标签的type属性值,也就是自定义的”com.generator.MySQLCommentGenerator”类,放到Context实例中。

4.2 调用生成java文件和Mapper文件的方法
xml配置文件解析完成,得到Configuration实例,后面生成文件的工作都会从Configuration实例中获取所需数据。生成文件的方法主要步骤为:1.连接数据库,查询表信息与列信息,2.生成文件内容,3.写入生成文件。
其中生成文件内容时,会根据Context的type属性反射创建MySQLCommentGenerator实例,然后调用自定义的生成注释方法。
如:生成实体类文件的注释,调用addModelClassComment方法

生成字段注释,调用addFieldComment方法

生成Get方法注释,调用addGetterComment方法

在调用addModelClassComment,addFieldComment,addGetterComment等生成注释的方法时,执行的都是MySQLCommentGenerator类的方法,这样就实现了生成自定义注释的功能。
5 总结
通过使用自定义实现CommentGenerator接口,让自动生成的代码加上我们想要的注释,可以省去自己加注释的麻烦。
与一般使用Mybatis Generator生成代码的方式一样,多实现个接口即可。
使用Maven方式运行时,需要在pom.xml引入插件时,依赖自己jar包。
把Mybatis Generator生成的代码加上想要的注释的更多相关文章
- mybatis Generator生成代码及使用方式
本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5889312.html 为什么要有mybatis mybatis 是一个 Java 的 ORM 框架,OR ...
- mybatis自动生成java代码
SSM框架没有DB+Record模式,写起来特别费劲,只能用下面的方法勉强凑合. 上图中,*.jar为下载的,src为新建的空白目录,.xml配置如下. <?xml version=" ...
- MyBatis Generator生成DAO——序列化
MyBatis Generator生成DAO 的时候,生成的类都是没有序列化的. 还以为要手工加入(開始是手工加入的),今天遇到分页的问题,才发现生成的时候能够加入插件. 既然分页能够有插件.序列化是 ...
- 【记录】Mybatis Generator生成数据对象Date/TimeStamp 查询时间格式化
Mybatis Generator是很好的工具帮助我们生成表映射关联代码,最近博主遇到一个问题,找了很久才解决, 就是用Mybatis Generator生成实体类的时候,Date 时间无法格式化输出 ...
- 使用MyBatis Generator自动创建代码
SSM框架--使用MyBatis Generator自动创建代码 1. 目录说明 使用自动生成有很多方式,可以在eclipse中安装插件,但是以下将要介绍的这种方式我认为很轻松,最简单,不需要装插件, ...
- MyBatis Generator自动创建代码
MyBatis Generator自动创建代码 1.首先在eclipse上安装mybatis插件 2.创建一个mavenWeb项目. 3.在resource中写入一个xml,一定要与我得同名 < ...
- 利用org.mybatis.generator生成实体类
springboot+maven+mybatis+mysql 利用org.mybatis.generator生成实体类 1.添加pom依赖: 2.编写generatorConfig.xml文件 ( ...
- MyBatis Generator 生成的example 使用 and or 简单混合查询
MyBatis Generator 生成的example 使用 and or 简单混合查询 参考博客:https://www.cnblogs.com/kangping/p/6001519.html 简 ...
- Maven下用MyBatis Generator生成文件
使用Maven命令用MyBatis Generator生成MyBatis的文件步骤如下: 1.在mop文件内添加plugin <build> <finalName>KenShr ...
- SpringBoot(十一):springboot2.0.2下配置mybatis generator环境,并自定义字段/getter/settetr注释
Mybatis Generator是供开发者在mybatis开发时,快速构建mapper xml,mapper类,model类的一个插件工具.它相对来说对开发者是有很大的帮助的,但是它也有不足之处,比 ...
随机推荐
- 【设计模式】Java设计模式 - 外观模式
Java设计模式 - 外观模式 不断学习才是王道 继续踏上学习之路,学之分享笔记 总有一天我也能像各位大佬一样 原创作品,更多关注我CSDN: 一个有梦有戏的人 准备将博客园.CSDN一起记录分享自己 ...
- 重复造轮子 SimpleMapper
接手的项目还在用 TinyMapper 的一个早期版本用来做自动映射工具,TinyMapper 虽然速度快,但在配置里不能转换类型,比如 deleted 在数据库中用 0.1 表示,转换成实体模型时没 ...
- [C/C++]C语言-踩坑记录
很久没写C语言的代码,发现很多小细节,记下来备查. 0. C语言常规头文件 #include <stdlib.h> #include <stdio.h> 1. 二维数组的开辟和 ...
- 7.第六篇 二进制安装 kube-apiserver
文章转载自:https://mp.weixin.qq.com/s?__biz=MzI1MDgwNzQ1MQ==&mid=2247483812&idx=1&sn=e6773e56 ...
- 阿里云下配置keepalive,利用HAVIP实现HA
注:这篇文章参考网络,有些称呼都变了,比如阿里云上的现在是弹性ip 包括阿里云在内的很多云环境,因为不支持浮动IP广受诟病.目前阿里云在VPC网络下发布了HAVIP,能够实现arp宣告IP.这样也就让 ...
- Centos7主机安装Cockpit管理其他主机
前提条件:需要管理的每台服务器上都需要安装cockpit 假设Centos7主机安装Cockpit的为A,其他主机为B 如果B上有A的公钥,那么直接连接至B,否则,输入B的用户名密码连接. 问题:在A ...
- ConfigMap使用说明
ConfigMap概述 ConfigMap供容器使用的典型用法如下. (1)生成为容器内的环境变量. (2)设置容器启动命令的启动参数(需设置为环境变量). (3)以Volume的形式挂载为容器内部的 ...
- k8s中yaml文件常见参数含义
apiVersion: apps/v1 #与k8s集群版本有关,使用 kubectl api-versions 即可查看当前集群支持的版本 kind: Deployment #该配置的类型,我们使用的 ...
- Windows上Navicat工具远程连接PostgreSQL数据库
首先,在pgdata(也就是在安装pg时指定的存放数据的文件见中)文件夹中,找到pg_hba.conf文件,在文件最后写入下面的内容: host all all 0.0.0.0/0 trust 接着, ...
- JSP实现登录删除添加星座等(带样式)
功能要求 1.完成两个页面 2.第一个登陆页面login. jsp 3.第二个用户管理页面useManage. jsp 4.有登录功能(能进行用户名密码的校验,用户名若为自己的学号密码为班级号,允许登 ...