一、文件示例
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"/> <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/> <plugin type="cn.z2huo.mybatis.generator.mybatis3.ModelGeneratorPlugin"> <property name="author" value="z2huo"/> </plugin> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true"/> <property name="dateFormat" value="yyyy-MM-dd"/> <property name="addRemarkComments" value="false"/> <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> <property name="forceBigDecimals" value="false" /> <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" /> <property name="exampleTargetPackage" value="cn.z2huo.demo.model.example"/> <property name="immutable" value="false"/> <property name="constructorBased" value="false"/> </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
中的 forceBigDecimals
和 useJSR310Types
属性来控制生成实体类的字段类型。
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; }
@Override public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { 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) { return false; } @Override public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { 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(" */"); 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
OB links
[[MyBatis Generator XML 配置文件参考]]
#MyBatis