尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

MyBatis代码生成器实战:提升开发效率300%

MyBatis代码生成器实战:提升开发效率300% 1. Mybatis代码生成器实战指南作为一名常年使用Mybatis的开发者我深刻理解手动编写Mapper接口、XML映射文件和实体类的痛苦。每次新增表结构都要重复这些机械劳动不仅效率低下还容易出错。今天要分享的是我在多个生产项目中验证过的Mybatis代码生成器解决方案它能将开发效率提升300%以上。这个生成器的核心价值在于通过配置数据库连接信息自动扫描表结构生成符合Mybatis规范的POJO、Mapper接口和XML文件。支持自定义模板、字段类型映射、注释生成等实用功能。无论是新项目初始化还是老项目维护都能显著减少CRUD代码的编写时间。2. 核心原理与架构设计2.1 生成器工作原理Mybatis官方提供的mybatis-generator-core是这套方案的基础引擎。它的工作流程可以分为四个阶段配置解析读取XML或properties格式的配置文件获取JDBC连接、生成路径等参数元数据采集通过JDBC连接数据库读取表结构、字段类型、主键、注释等信息模板渲染根据内置或自定义的模板文件将元数据填充到Velocity/FreeMarker模板中文件输出按照包结构生成Java实体类、Mapper接口和XML映射文件关键提示生成器默认使用XML配置方式但在Spring Boot项目中我更推荐使用Java Config配置便于与现有项目集成。2.2 技术栈选型对比当前主流的代码生成方案主要有三种实现方式方案类型优点缺点适用场景MyBatis官方生成器功能完善文档齐全配置复杂扩展性一般传统SSM项目MyBatis-Plus开箱即用零配置定制化能力较弱快速原型开发自定义模板引擎完全可控灵活度高开发成本高有特殊规范要求的项目经过多个项目验证我最终选择基于MyBatis官方生成器进行二次开发。它在保证稳定性的同时通过插件机制提供了足够的扩展空间。以下是核心依赖配置dependency groupIdorg.mybatis.generator/groupId artifactIdmybatis-generator-core/artifactId version1.4.1/version /dependency dependency groupIdorg.freemarker/groupId artifactIdfreemarker/artifactId version2.3.31/version /dependency3. 完整实现步骤3.1 基础环境配置首先创建generatorConfig.xml配置文件这是生成器的核心?xml version1.0 encodingUTF-8? !DOCTYPE generatorConfiguration PUBLIC -//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd generatorConfiguration context idmysql targetRuntimeMyBatis3 jdbcConnection driverClasscom.mysql.cj.jdbc.Driver connectionURLjdbc:mysql://localhost:3306/your_db userIdroot password123456 /jdbcConnection javaModelGenerator targetPackagecom.example.entity targetProjectsrc/main/java/ sqlMapGenerator targetPackagemapper targetProjectsrc/main/resources/ javaClientGenerator typeXMLMAPPER targetPackagecom.example.mapper targetProjectsrc/main/java/ table tableName% generatedKey columnid sqlStatementMySQL identitytrue/ /table /context /generatorConfiguration关键参数说明jdbcConnection: 配置数据库连接信息javaModelGenerator: 实体类生成位置sqlMapGenerator: XML映射文件生成位置table: 支持通配符%匹配所有表也可指定具体表名3.2 自定义模板开发默认生成的代码风格可能不符合项目规范这时需要自定义模板。以实体类模板为例在resources下创建template/entity.ftl文件编写Freemarker模板内容package ${package}; import java.io.Serializable; #list importList as import import ${import}; /#list /** * ${tableRemark!}实体类 */ public class ${className} implements Serializable { private static final long serialVersionUID 1L; #list columns as column /** ${column.remarks!} */ private ${column.javaType} ${column.javaProperty}; /#list #list columns as column public ${column.javaType} get${column.javaProperty?cap_first}() { return ${column.javaProperty}; } public void set${column.javaProperty?cap_first}(${column.javaType} ${column.javaProperty}) { this.${column.javaProperty} ${column.javaProperty}; } /#list }然后在generatorConfig.xml中配置模板路径context property namejavaFileEncoding valueUTF-8/ property nametemplatePath valuesrc/main/resources/template/ plugin typeorg.mybatis.generator.plugins.SerializablePlugin/ /context3.3 执行生成命令创建GeneratorRunner类作为启动入口public class GeneratorRunner { public static void main(String[] args) throws Exception { ListString warnings new ArrayList(); ConfigurationParser cp new ConfigurationParser(warnings); Configuration config cp.parseConfiguration( GeneratorRunner.class.getResourceAsStream(/generatorConfig.xml)); DefaultShellCallback callback new DefaultShellCallback(true); MyBatisGenerator generator new MyBatisGenerator(config, callback, warnings); generator.generate(null); warnings.forEach(System.out::println); } }执行后会在指定目录生成如下结构src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── example/ │ │ ├── entity/ # 实体类 │ │ └── mapper/ # Mapper接口 │ └── resources/ │ └── mapper/ # XML映射文件4. 高级功能实现4.1 字段类型自定义映射数据库字段类型与Java类型默认映射可能不符合需求可以通过javaTypeResolver配置javaTypeResolver property nameforceBigDecimals valuefalse/ property nameuseJSR310Types valuetrue/ /javaTypeResolver常用类型映射规则DATE → java.time.LocalDateTIMESTAMP → java.time.LocalDateTimeDECIMAL → java.math.BigDecimalTINYINT → Integer (当长度1时)4.2 自定义注释生成通过CommentGenerator插件可以增强代码注释public class CustomCommentGenerator extends DefaultCommentGenerator { Override public void addFieldComment(Field field, IntrospectedTable table, IntrospectedColumn column) { field.addJavaDocLine(/**); if (column.getRemarks() ! null) { field.addJavaDocLine( * column.getRemarks()); } field.addJavaDocLine( * 列名: column.getActualColumnName()); field.addJavaDocLine( */); } }在配置中注册插件commentGenerator typecom.example.CustomCommentGenerator/4.3 逻辑删除与乐观锁支持对于包含逻辑删除字段和版本号字段的表可以配置特殊处理table tableNameuser property namesoftDeleteColumn valueis_deleted/ property nameoptimisticLockColumn valueversion/ /table生成代码时会自动添加相关逻辑// 在Mapper接口中生成 int updateWithOptimisticLock(User user);5. 常见问题解决方案5.1 表字段与关键字冲突当表字段名是SQL关键字时XML中需要特殊处理resultMap result columnorder propertyorder jdbcTypeVARCHAR/ /resultMap select idselectByExample resultMapBaseResultMap select include refidBase_Column_List / from user where order #{order,jdbcTypeVARCHAR} /select关键技巧使用反引号包裹字段名或者在配置中开启自动转义property namebeginningDelimiter value/ property nameendingDelimiter value/5.2 多表关联查询支持生成器默认不处理关联关系需要手动扩展创建DTO类继承生成的实体类在XML中添加关联查询resultMap idUserWithRole extendsBaseResultMap typecom.example.dto.UserDTO collection propertyroles ofTypecom.example.entity.Role id columnrole_id propertyid/ result columnrole_name propertyname/ /collection /resultMap select idselectWithRole resultMapUserWithRole select u.*, r.id as role_id, r.name as role_name from user u left join user_role ur on u.id ur.user_id left join role r on ur.role_id r.id where u.id #{id} /select5.3 生成代码风格统一通过实现Plugin接口可以统一代码风格public class LombokPlugin extends PluginAdapter { Override public boolean modelBaseRecordClassGenerated(TopLevelClass clazz, IntrospectedTable table) { clazz.addImportedType(lombok.Data); clazz.addAnnotation(Data); return true; } }配置使用plugin typecom.example.LombokPlugin/6. 性能优化实践6.1 增量生成策略大型项目全量生成耗时严重可以采用增量策略// 在GeneratorRunner中添加过滤逻辑 SetString existFiles scanExistingFiles(); generator.generate(new ProgressCallback() { Override public void introspectionStarted(int totalTasks) {} Override public void generationStarted(int totalTasks) {} Override public void saveStarted(int totalTasks) {} Override public void startTask(String taskName) { if(existFiles.contains(taskName)) { throw new SkipTaskException(); } } });6.2 多线程生成对于数百张表的情况可以并行生成ExecutorService executor Executors.newFixedThreadPool(8); ListFuture? futures new ArrayList(); for (String table : tables) { futures.add(executor.submit(() - { Configuration config createConfigForTable(table); MyBatisGenerator generator new MyBatisGenerator(config, ...); generator.generate(null); })); } futures.forEach(f - { try { f.get(); } catch (Exception e) { e.printStackTrace(); } });6.3 生成缓存机制为避免重复解析表结构可以引入缓存public class CachedIntrospector extends DefaultIntrospector { private static MapString, IntrospectedTable cache new ConcurrentHashMap(); Override public IntrospectedTable introspectTable(TableConfiguration config, DatabaseMetaData metaData) throws SQLException { return cache.computeIfAbsent(config.getTableName(), k - super.introspectTable(config, metaData)); } }在配置中指定introspector typecom.example.CachedIntrospector/7. 工程化集成方案7.1 Maven插件集成将生成器作为构建环节的一部分build plugins plugin groupIdorg.mybatis.generator/groupId artifactIdmybatis-generator-maven-plugin/artifactId version1.4.1/version executions execution idgenerate-model/id phasegenerate-sources/phase goals goalgenerate/goal /goals /execution /executions configuration configurationFilesrc/main/resources/generatorConfig.xml/configurationFile overwritetrue/overwrite /configuration /plugin /plugins /build执行命令mvn mybatis-generator:generate7.2 Spring Boot Starter开发创建自定义starter实现自动生成定义自动配置类Configuration ConditionalOnClass(MyBatisGenerator.class) EnableConfigurationProperties(GeneratorProperties.class) public class GeneratorAutoConfiguration { Bean ConditionalOnMissingBean public GeneratorRunner generatorRunner(GeneratorProperties properties) { return new GeneratorRunner(properties); } }添加spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration\ com.example.autoconfigure.GeneratorAutoConfiguration应用配置mybatis: generator: jdbc-url: jdbc:mysql://localhost:3306/db model-package: com.example.entity mapper-package: com.example.mapper7.3 可视化界面实现对于非技术人员可以开发Web界面RestController RequestMapping(/generator) public class GeneratorController { PostMapping public String generate(RequestBody GeneratorRequest request) { GeneratorConfig config convertToConfig(request); MyBatisGenerator generator new MyBatisGenerator(config, ...); generator.generate(null); return 生成成功; } }前端界面提供数据库连接配置表选择器生成选项设置实时日志展示8. 实际项目经验总结在金融项目中我们遇到了分库分表场景通过扩展TableConfiguration支持了表名模式匹配table expressiont_order_[0-9]{4} domainObjectNameOrder mapperNameOrderMapper/生成器会扫描所有匹配t_order_0000到t_order_9999的表合并生成统一的Order实体和Mapper在XML中使用动态SQLselect idselectById resultMapBaseResultMap foreach collectiontableSuffixes itemsuffix select * from t_order_${suffix} where id#{id}; /foreach /select另一个电商项目中我们通过自定义TypeHandler实现了JSON字段自动映射public class JsonTypeHandler extends BaseTypeHandlerMapString, Object { private static final ObjectMapper mapper new ObjectMapper(); Override public void setNonNullParameter(PreparedStatement ps, int i, MapString, Object parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, mapper.writeValueAsString(parameter)); } // 其他方法省略... }在生成器配置中注册table tableNameproduct columnOverride columnspecs javaTypejava.util.Map typeHandlercom.example.JsonTypeHandler/ /table这些实战经验表明MyBatis代码生成器不仅适用于简单CRUD场景通过合理扩展完全可以满足复杂业务需求。关键在于理解其扩展机制根据项目特点进行定制化开发。
返回列表