maven 项目中,整合了 MyBatis 后,可以集成 mybatis generator 插件来生成数据库表对应的 Java Bean、 以及 MyBatis 的 mapper 文件。
首先在pom.xml
添加插件:
org.mybatis.generatormybatis-generator-maven-plugin1.3.7truetruemysqlmysql-connector-java8.0.15
然后将插件的配置文件generatorConfig.xml
放在resources
目录:
jdbcConnection
标签是用来配置数据库连接的。
修改javaModelGenerator
、sqlMapGenerator
、javaClientGenerator
标签中的targetPackage
属性来配置生成文件保存的目录即可。
最后边的table
标签用来配置生成单表的文件还是全部表的文件。
最后编译项目,运行如下插件即可:

生成的目标文件如下:


但是里边的注释乱七八糟的,额外添加了许多没用的:


这是由于插件生成注解时默认使用DefaultCommentGenerator
类,我们理想的情况是只在生成数据库表对应的 Java Bean 时添加表以及字段的注释即可。
所以就需要自定义注解生成的类,先添加依赖:
org.mybatis.generatormybatis-generator-core1.3.7
自定义的注解生成类如下,需要实现CommentGenerator
接口:
public class MyCommentGenerator implements CommentGenerator {
private Properties properties;
public MyCommentGenerator() {
properties = new Properties();
}
@Override
public void addConfigurationProperties(Properties properties) {
// 获取自定义的 properties
this.properties.putAll(properties);
}
// 字段注解
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (StringUtils.isEmpty(introspectedColumn.getRemarks())) {
return;
}
// 获取字段注释
String remarks = introspectedColumn.getRemarks();
field.addJavaDocLine("/**");
field.addJavaDocLine(" * " + remarks);
field.addJavaDocLine(" */");
}
// 类注解
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
String author = properties.getProperty("author");
// 获取表注释
String remarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + remarks);
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" */");
}
}
然后在generatorConfig.xml
中修改注解生成器的配置,指定我们自定义的注释生成类:
由于使用了自定义的注释生成类,所以无法像前边那样直接运行插件完成操作,需要我们通过代码来执行:
public class MyGenerator {
public static void main( String[] args ) throws Exception {
List warnings = new ArrayList();
File configFile = new File("src/main/resources/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
运行后,再看User
类的注释,就符合我们的预期了:
