mybatis generator为实体类生成自定义注释(读取数据库字段的注释添加到实体类,不修改源码)
我们都知道mybatis generator自动生成的注释没什么实际作用,而且还增加了代码量。如果能将注释从数据库中捞取到,不仅能很大程度上增加代码的可读性,而且减少了后期手动加注释的工作量。
1、首先定义注释生成插件
MyCommentGenerator.java
package com.ilovey.mybatis.comment;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* mybatis generator生成注释插件
* <p>
* Created by huhaichao on 2017/5/15.
*/
public class MyCommentGenerator extends DefaultCommentGenerator {
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 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().replace("\n", " "));
field.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
}
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
}
2、然后为mybatisgenerator配置插件
<?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="context1">
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 使用自定义的插件 -->
<commentGenerator type="com.ilovey.mybatis.comment.MyCommentGenerator">
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8"
userId="root" password="123456">
</jdbcConnection>
<javaModelGenerator targetPackage="com.ilovey.biz.entity.base"
targetProject="ilovey.biz/src/main/java"/>
<sqlMapGenerator targetPackage="com.ilovey.biz.mapper.base"
targetProject="ilovey.biz/src/main/resources"/>
<javaClientGenerator targetPackage="com.ilovey.biz.mapper.base"
targetProject="ilovey.biz/src/main/java" type="XMLMAPPER"/>
<table tableName="us_user_info" domainObjectName="UsUserInfo">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
3、使用mybatis generator自动生成代码
由于使用的是maven项目,而且使用了了自定义的插件,所以采用 main方法启动,适用场景更对,而且能将代码生成到对应的工程目录下,免去拷贝的过程(当然也可以用maven插件、控制台、eclipse插件等多种方式启动)。
注意:当前类所在的工程要添加mybatis generator的依赖包
启动类如下
package com.ilovey.mybatis;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* 运行此方法生成mybatis代码
* 生成代码自动放入对应目录
* 配置文件targetProject应从项目名称开始到要生成到的classpath
* Created by huhaichao on 2017/5/15.
*/
public class MyBatisGeneratorRun {
public static void main(String[] args) throws Exception{
MyBatisGeneratorRun app = new MyBatisGeneratorRun();
System.out.println(app.getClass().getResource("/").getPath());
app.generator();
System.out.println(System.getProperty("user.dir"));
}
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(resourceAsStream);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for(String warning:warnings){
System.out.println(warning);
}
}
}
再贴下项目的maven依赖,有需要的可以看下
<?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>party.lovey</groupId>
<artifactId>generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
</project>
4、生成效果
package com.ilovey.biz.entity.base;
import java.io.Serializable;
import java.util.Date;
public class UsUserInfo implements Serializable {
/**
*
*/
private Integer id;
/**
* 用户id
*/
private Integer userId;
/**
* 昵称
*/
private String nickName;
/**
* 头像
*/
private String headImage;
/**
* 手机号码
*/
private String mobile;
/**
* 性别(0保密,1男,2女)
*/
private Integer sex;
/**
* 地区
*/
private Integer region;
/**
* 个性签名
*/
private String signature;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
//setter 和 getter方法省略
}
此外,mybatis的插件还有着更强大的功能,比如支持分页功能,修复因别名造成的delete语句错误等,需要这些插件的朋友可以在底部留言。
原文地址:https://www.cnblogs.com/cblogs/p/9432129.html