我们都知道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&amp;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

mybatis generator为实体类生成自定义注释(读取数据库字段的注释添加到实体类,不修改源码)的更多相关文章

  1. mybatis generator cmd 终端命令 生成dao model mapper

    mybatis generator cmd 终端命令 生成dao model mapper 文件包下载 mybatis-generator-core-1.3.2.jar 下载地址:https://gi ...

  2. 业务类接口在TCP,HTTP,BLL模式下的实例 设计模式混搭 附源码一份

    业务类接口在TCP,HTTP,BLL模式下的实例 设计模式混搭 附源码一份 WinForm酒店管理软件--框架这篇随笔可以说是我写的最被大家争议的随笔,一度是支持和反对是一样的多.大家对我做的这个行业 ...

  3. Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)

    在看本篇之前,最好先看一下上一篇通过实现CommentGenerator接口的方法来实现中文注释的例子,因为很多操作和上一篇基本是一致的,所以本篇可能不那么详细. 首先说一下上篇通过实现Comment ...

  4. idea集成 MyBatis Generator 插件,自动生成dao,model,sql map文件

    1.集成到开发环境中 以maven管理的功能来举例,只需要将插件添加到pom.xml文件中即可.(注意此处是以plugin的方式,放在<plugins></plugins>中间 ...

  5. 使用mybatis generator插件,自动生成dao、dto、mapper等文件

    mybatis generator 介绍 mybatis generator中文文档http://mbg.cndocs.tk/ MyBatis Generator (MBG) 是一个Mybatis的代 ...

  6. mybatis generator maven插件自动生成代码

    如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...

  7. mybatis generator对于同一个表生成多次代码的问题

    原文:https://blog.csdn.net/jiangjun0130/article/details/83055336 现象: mybatis generator是一个持久层代码自动生成工具,能 ...

  8. mybatis generator.xml 配置 自动生成model,dao,mapping

    generator.xml文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE gener ...

  9. C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

    [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系型数据库,在使用了多年的Sql_Helper_DG后,由于项目需 ...

随机推荐

  1. 170616、解决 java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList

    报错截图: 原因:搭建项目的时候,springmvc默认是没有对象转换成json的转换器的,需要手动添加jackson依赖. 解决步骤: 1.添加jackson依赖到pom.xml <!-- j ...

  2. 170524、java.lang.IllegalArgumentException: No converter found for return value of type异常解决

    错误原因及解决步骤 1.原因:这是因为springmvc默认是没有对象转换成json的转换器的,需要手动添加jackson依赖. 2.解决步骤: 手动添加jackson依赖到pom.xml文件中 &l ...

  3. Feature Toggle JUnit

    Feature Toggle,简单来说,就是一个开关,将未完成功能的代码屏蔽后发布到生产环境,从而避免多分支的情况.之所以有本文的产生,就是源于此情景.在引入Feature Toggle的同时,我们发 ...

  4. 沈阳网络赛F-Fantastic Graph【贪心】or【网络流】

    "Oh, There is a bipartite graph.""Make it Fantastic." X wants to check whether a ...

  5. Oracle HA 之ADVM和ACFS

    --ADVM ADVM主要是为了使除了数据库之外的第三方应用程序也可以使用asm存储,这样不限于使asm局限于自家的数据库领域.要想使用ADVM首先必须安装grid,已经创建好了asm磁盘,asm磁盘 ...

  6. Constructor Overloading in Java with examples 构造方法重载 Default constructor 默认构造器 缺省构造器 创建对象 类实例化

    Providing Constructors for Your Classes (The Java™ Tutorials > Learning the Java Language > Cl ...

  7. centos7 iptables/firewalld docker open port

    here are multiple "hackish" ways to do it: scan kernel logs, as mentioned by Jiri (but you ...

  8. flask中secret_key的作用

    https://segmentfault.com/q/1010000007295395

  9. Grafana+Prometheus监控

    添加模板一定要看说明以及依赖 监控redis https://blog.52itstyle.com/archives/2049/ http://www.cnblogs.com/sfnz/p/65669 ...

  10. js基础面试高频面点1:变量提升

    一.什么是变量提升?var变量提升的底层原理是什么? 变量提升的定义:所有变量的声明语句都会被提升到代码头部,这就是变量提升. 原理:引擎在读取js代码的过程中,分为两步,专业来说代码运行是分为预处理 ...