一、文件示例
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
| <?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-mybatis-plus-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 78 79 80 81 82 83
| <!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="flat"> <property name="javaFileEncoding" value="UTF-8"/> <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/> <plugin type="cn.z2huo.mybatis.generator.mybatisplus.ModelGeneratorPlugin"> <property name="author" value="z2huo"/> </plugin> <plugin type="cn.z2huo.mybatis.generator.mybatisplus.plugins.DisableAllMethodPlugin"/> <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-mybatis-plus-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-mybatis-plus-generator/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.z2huo.demo.dao" targetProject="model/generator/model-mybatis-plus-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="flat"
属性,用来指定生成的实体类对象中的所有字段都在一个类中,不会因为实体类的主键字段包括两个及以上而单独生成主键类。
commentGenerator
生成类注释定义,可以在这里生成,也可以在 Plugin
中生成注释。
javaTypeResolver
中的 forceBigDecimals
和 useJSR310Types
属性来控制生成实体类的字段类型。
plugin
中定义了一下插件,这些插件用于限制生成 DAO
文件时,不生成方法,因为 MyBatis-plus
需要继承 BaseMapper
,DAO
中不需要任何方法
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
4.1 自定义生成文件插件
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
| public class ModelGeneratorPlugin extends PluginAdapter {
private static final List<String> BASE_DO_FIELD_NAME_LIST = List.of("createTime", "operateTime", "createByCode", "operateByCode"); private static final List<String> CREATE_FIELD_NAME_LIST = List.of("createTime", "createByCode"); public static final List<String> OPERATE_FIELD_NAME_LIST = List.of("operateTime", "operateByCode"); public static final String ID_KEY = "id"; private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private FullyQualifiedJavaType doModelJavaType;
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.addImportedType("com.baomidou.mybatisplus.annotation.TableName"); topLevelClass.addAnnotation("@Data"); topLevelClass.addAnnotation("@NoArgsConstructor"); topLevelClass.addAnnotation(String.format("@TableName(\"%s\")", introspectedTable.getFullyQualifiedTable().getIntrospectedTableName())); 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(" */"); doModelJavaType = topLevelClass.getType(); return true; }
@Override public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { if (BASE_DO_FIELD_NAME_LIST.contains(field.getName())) { topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.FieldFill"); topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.TableField"); } if (introspectedTable.hasPrimaryKeyColumns()) { topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.IdType"); topLevelClass.addImportedType("com.baomidou.mybatisplus.annotation.TableId"); if (introspectedTable.getPrimaryKeyColumns().size() == 1) { if (ID_KEY.equals(introspectedTable.getPrimaryKeyColumns().getFirst().getActualColumnName()) && ID_KEY.equals(introspectedColumn.getActualColumnName())) { field.addAnnotation("@TableId(type = IdType.ASSIGN_ID)"); } } else if (introspectedTable.getPrimaryKeyColumns().size() > 1){ if (introspectedTable.getPrimaryKeyColumns().contains(introspectedColumn)) { field.addAnnotation("@TableId(type = IdType.INPUT)"); } } } if (CREATE_FIELD_NAME_LIST.contains(field.getName())) { field.addAnnotation("@TableField(fill = FieldFill.INSERT)"); } else if (OPERATE_FIELD_NAME_LIST.contains(field.getName())) { field.addAnnotation("@TableField(fill = FieldFill.INSERT_UPDATE)"); } 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 sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) { 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"); FullyQualifiedJavaType baseMapperJavaType = new FullyQualifiedJavaType("com.baomidou.mybatisplus.core.mapper.BaseMapper"); baseMapperJavaType.addTypeArgument(doModelJavaType); interfaze.addImportedType(baseMapperJavaType); interfaze.addSuperInterface(baseMapperJavaType); return true; } private String date2Str(LocalDate date) { return date.format(dateTimeFormatter); } }
|
- 给生成的实体类添加类注释
- 给生成的实体类添加
Lombok
注解
- 给生成的实体类添加
MyBatis-plus
注解
- 给生成的实体类的字段添加字段注释
- 给生成的实体类的字段添加
MyBatis-plus
注解
- 给生成的 DAO 文件添加注释和
Spring
注解
- 使生成的 DAO 文件继承
MyBatis-plus
的 BaseMapper
- 生成的实体类不生成 Getter 和 Setter 方法
4.2 自定义 DAO 方法是否生成插件
4.2.1 禁止生成 delete 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class CustomDisableDeletePlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean clientDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralDeleteMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } }
|
4.2.2 禁止生成 select 方法
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
| public class CustomDisableSelectPlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicSelectManyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicSelectOneMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralSelectDistinctMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientGeneralSelectMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectListFieldGenerated(Field field, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectOneMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientSelectAllMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientCountByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } }
|
4.2.3 禁止生成 update 方法
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
| public class CustomDisableUpdatePlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean clientGeneralUpdateMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateAllColumnsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateSelectiveColumnsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } }
|
4.2.4 禁止生成 insert 方法
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
| public class CustomDisableInsertPlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean clientBasicInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientBasicInsertMultipleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertMultipleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } @Override public boolean clientInsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { return false; } }
|
4.2.5 组合插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class DisableAllMethodPlugin extends CompositePlugin { public DisableAllMethodPlugin() { super.addPlugin(new CustomDisableInsertPlugin()); super.addPlugin(new CustomDisableDeletePlugin()); super.addPlugin(new CustomDisableUpdatePlugin()); super.addPlugin(new CustomDisableSelectPlugin()); } @Override public boolean validate(List<String> warnings) { return true; } }
|
5、启动类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class MybatisPlusGeneratorMain { 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