MyBatis是流行的持久化框架,通过抽象底层的JDBC代码,在类对象和数据库列之间自动映射SQL的参数和结果,以SQL为映射的间接层,实现SQL映射器。MyBatis Generator (MBG) 是一个Mybatis的代码生成器,内省数据库的表,然后自动生成映射表的实体类,并生成CRUD(插入,查询,更新,删除)操作的样板代码。MyBatis,之前所在的公司在用,生成器也在用。虽然生成器大大提供了开发效率,但生成的代码可读性比较低,尤其是自动生成的实体类,如下:
1 | /** |
这些自动生成注释,没有实质性信息,其实真正有用的是,设计表时,该字段的用途,即表字段的注释。
addRemarkComments选项
庆幸的是,MyBatis生成器在版本1.3.3中添加了,addRemarkComments
选项 [github],可以在生成的实体类中附带表字段的注释。addRemarkComments
官方文档的介绍 [doc]:
This property is used to specify whether MBG will include table and column remarks from db table in the generated comments. The property supports these values:
- false: This is the default value When the property is false or unspecified, all generated comments will not include table and column remarks from db table when the element was generated.
- true: When the property is true, table and columns remarks from db table will be added to the generated comments.
Warning: If suppressAllComments option is true, this option will be ignored.
使用方法很简单,只需将MyBatis生成器的配置文件中的commentGenerator
节点修改为:
1 | <commentGenerator> |
自定义注释生成器类
通过addRemarkComments
选项生成的实体类的注释不够精简。于是笔者参考MyBatis的默认的注释生成器DefaultCommentGenerator
[github],对其进行改造成如下:
1 | package com.test.mbg; |
MyBatis的配置文件修改为:
1 | <commentGenerator type="com.test.mbg.RemarksCommentGenerator"> |
运行MyBatis生成器
改用自定义的RemarksCommentGenerator
后,运行MyBatis插件可能会报错。需要使用Java来运行MyBatis生成器,代码如下 [doc]:
1 | package com.test.mbg; |