一、文件示例

1、POM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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>
<parent>
<groupId>cn.z2huo</groupId>
<artifactId>generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>model-mybatis3-generator</artifactId>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>

<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency>

</dependencies>

</project>

2、generatorConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!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="simple" targetRuntime="MyBatis3" defaultModelType="conditional">

<property name="javaFileEncoding" value="UTF-8"/>

<!--生成mapper.xml时覆盖原文件-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
<plugin type="cn.z2huo.mybatis.generator.mybatis3.ModelGeneratorPlugin">
<!-- 通过property定义的属性,可以在代码中进行读取 -->
<!-- 生成的文件注释中的作者 -->
<property name="author" value="z2huo"/>
</plugin>

<!-- <commentGenerator type="cn.z2huo.mybatis.generator.mybatis3.CustomCommentGenerator" >-->
<commentGenerator>
<!-- 是否去除自动生成的注释(所有类型的注释),将覆盖其他的配置 true false 默认true -->
<property name="suppressAllComments" value="true" />
<!-- 是否去除日期部分的注释 true false 默认 true-->
<property name="suppressDate" value="true"/>
<property name="dateFormat" value="yyyy-MM-dd"/>
<!-- 是否应该在注释中添加表或列注释 true false 默认 false-->
<property name="addRemarkComments" value="false"/>
<!-- 是使用 javax 注释,还是使用 jakarta false为javax true为jakarta-->
<property name="useLegacyGeneratedAnnotation" value="false"/>
</commentGenerator>

<!-- 数据库连接设置 -->
<jdbcConnection driverClass="org.postgresql.Driver"
connectionURL="jdbc:postgresql://localhost:5432/mybatis_plus_demo?current_schema=public"
userId="postgres"
password="z2huo@2024"
/>

<javaTypeResolver>
<!-- 默认false,把JDBC DECIMAL和NUMERIC类型解析为Integer,为true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<property name="forceBigDecimals" value="false" />
<!-- 默认false,把日期时间相关数据类型映射为 JSR310 的 LocalDate、LocalTime、LocalDateTime,日期时间数据类型包括 date、time、timestamp -->
<property name="useJSR310Types" value="true"/>
</javaTypeResolver>

<javaModelGenerator targetPackage="cn.z2huo.demo.model.dataobject"
targetProject="model/generator/model-mybatis3-generator/src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
<!-- 此属性用于为生成的 Example 类指定不同的包。如果未指定,则 Example 类将与其他实体对象生成在同一个包中。 -->
<property name="exampleTargetPackage" value="cn.z2huo.demo.model.example"/>
<!-- <property name="exampleTargetProject" value=""/>-->
<property name="immutable" value="false"/>
<property name="constructorBased" value="false"/>
<!-- 此属性可用于为生成的 Java 实体对象指定父类。 -->
<!-- <property name="rootClass" value="cn.z2huo.demo.model.BaseDO"/>-->
</javaModelGenerator>

<sqlMapGenerator targetPackage="mapper"
targetProject="model/generator/model-mybatis3-generator/src/main/resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>

<javaClientGenerator type="XMLMAPPER" targetPackage="cn.z2huo.demo.dao"
targetProject="model/generator/model-mybatis3-generator/src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>

<table tableName="z2huo_user" domainObjectName="user.UserDO" mapperName="user.UserDAO"/>
<table tableName="z2huo_role" domainObjectName="role.RoleDO" mapperName="role.RoleDAO"/>
<table tableName="z2huo_user_role_relation" domainObjectName="user.UserRoleRelationDO" mapperName="user.UserRoleRelationDAO"/>
<table tableName="z2huo_role_permission_relation" domainObjectName="role.RolePermissionRelationDO" mapperName="role.RolePermissionRelationDAO"/>
<table tableName="z2huo_permission" domainObjectName="permission.permissionDO" mapperName="permission.PermissionDAO" />
<table tableName="z2huo_system" domainObjectName="system.SystemDO" mapperName="system.SystemDAO" />

</context>

</generatorConfiguration>
  • context 元素的 defaultModelType="conditional" 属性,用来指定生成的实体类对象是可能会有继承关系的,当实体类的主键字段包括两个及以上时,会生成一个主键类,实体类继承该主键类。
  • commentGenerator 生成类注释定义,可以在这里生成,也可以在 Plugin 中生成注释。
  • javaTypeResolver 中的 forceBigDecimalsuseJSR310Types 属性来控制生成实体类的字段类型。

3、CommentGenerator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class CustomCommentGenerator implements CommentGenerator {  

private boolean suppressAllComments;

private boolean suppressDate;

private boolean addRemarkComments;

private Properties properties;

private Properties systemProperties;

public CustomCommentGenerator() {
properties = new Properties();
systemProperties = System.getProperties();

suppressAllComments = true;
suppressDate = true;
addRemarkComments = false;
}

@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = Boolean.parseBoolean(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = Boolean.parseBoolean(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
addRemarkComments = Boolean.parseBoolean(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));
}

@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}

StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
field.addJavaDocLine(sb.toString().replace("\n", " "));
field.addJavaDocLine(" */");
}

@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

if (suppressAllComments) {
return;
}

field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
if (StringUtility.stringHasValue(remarks)) {
String[] remarkLines = remarks.split(System.lineSeparator());
for (String remarkLine : remarkLines) {
field.addJavaDocLine(" * " + remarkLine);
}
} else {
field.addJavaDocLine(" * ");
}
field.addJavaDocLine(" */");
}

@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
CommentGenerator.super.addClassComment(innerClass, introspectedTable, markAsDoNotDelete);
}

}

4、Plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
public class ModelGeneratorPlugin extends PluginAdapter {  

public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

private String author;

@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
this.author = properties.getProperty("author");
}

@Override
public boolean validate(List<String> list) {
return true;
}

/**
* 为实体添加lombok的注解
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {

// import
topLevelClass.addImportedType("lombok.Data");
topLevelClass.addImportedType("lombok.NoArgsConstructor");

// 注解
topLevelClass.addAnnotation("@Data");
topLevelClass.addAnnotation("@NoArgsConstructor");

// 类上面添加注释
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * <p>DO对应数据库表为 " + introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(" * <p>");
topLevelClass.addJavaDocLine(" * ");
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" * @date " + this.date2Str(LocalDate.now()));
topLevelClass.addJavaDocLine(" */");

return true;
}

/**
* 为实体类字段添加注释
*/
@Override
public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
IntrospectedTable introspectedTable, ModelClassType modelClassType) {

field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
if (StringUtility.stringHasValue(remarks)) {
String[] remarkLines = remarks.split(System.lineSeparator());
for (String remarkLine : remarkLines) {
field.addJavaDocLine(" * " + remarkLine);
}
} else {
field.addJavaDocLine(" * ");
}
field.addJavaDocLine(" */");
return true;
}

@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成 getter
return false;
}

@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
// 不生成 setter
return false;
}

@Override
public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {

// 类上面添加注释
interfaze.addJavaDocLine("/**");
interfaze.addJavaDocLine(" * <p>DAO对应数据库表为 " + introspectedTable.getFullyQualifiedTable());
interfaze.addJavaDocLine(" * <p>");
interfaze.addJavaDocLine(" * ");
interfaze.addJavaDocLine(" * @author " + author);
interfaze.addJavaDocLine(" * @date " + this.date2Str(LocalDate.now()));
interfaze.addJavaDocLine(" */");

// 添加 spring 注解
interfaze.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Repository"));
interfaze.addAnnotation("@Repository");

return true;
}

private String date2Str(LocalDate date) {
return date.format(dateTimeFormatter);
}

}
  • 给生成的实体类添加类注释
  • 给生成的实体类添加 Lombok 注解
  • 给生成的实体类的字段添加字段注释
  • 给生成的 DAO 文件添加注释和 Spring 注解
  • 生成的实体类不生成 Getter 和 Setter 方法

5、启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Mybatis3GeneratorMain {  

public static void main(String[] args) throws XMLParserException, IOException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;

ClassPathResource classPathResource = new ClassPathResource("generatorConfig.xml");
File configFile = classPathResource.getFile();

ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println("\n=========== waring out ===========");
warnings.forEach(System.out::println);
}

}

相关链接

MyBatis Generator XML 配置文件参考 - z2huo

[[MyBatis Generator XML 配置文件参考]]

OB tags

#MyBatis