资讯动态

MyBatis 通用 Mapper 6 实战指南:JDK 17 + Jakarta JPA + Spring Boot 4 下的单表 CRUD 利器

发布时间:2026/10/15 18:00:52 来源:尧图企业网站定制
后端ORM数据库【免费下载链接】MapperMybatis Common Mapper - Easy to use项目地址https://gitcode.com/gh_mirrors/ma/Mapper点击查看免费下载本指南围绕 tk.mybatis 通用 Mapper 6.0.0仓库根目录 README.md展开系统讲解其版本选型、依赖引入、通用方法体系、Spring Boot 集成与全局配置并结合仓库源码core、base、extra 等模块揭示其 SQL 自动生成的底层原理。读完本文你将能够在 JDK 17 与 Spring Boot 4 项目中快速引入通用 Mapper用极少的代码完成单表增删改查并能按需设计属于自己的通用方法。为什么需要通用 Mapper传统 MyBatis 开发中每张表都要手写实体类、Mapper 接口与 XML或注解SQLselectByPrimaryKey、insert、updateByPrimaryKey、deleteByPrimaryKey这类样板代码重复度极高。通用 Mapper 解决的正是在此问题它把单表 CRUD 中套路化的方法预先定义在通用接口中由框架根据实体类上的 JPA 注解Table、Id、Column等在运行时自动生成对应 SQL。需要注意的是仓库 README 明确说明了其能力边界极其方便地使用 MyBatis 单表的增删改查支持单表操作不支持通用的多表联合查询。多表查询仍应使用手写 SQLXML 或注解方式完成。同时通用 Mapper 允许你随意的按照自己的需要选择通用方法也可以很方便的开发自己的通用方法这是其可扩展性设计的核心。版本与分支选择通用 Mapper 6 与不同 Spring Boot 大版本严格对应请根据项目实际情况选择对应分支。以下是仓库 README.md 中给出的版本匹配表分支Spring Boot 版本JDK 版本Mapper 版本masterSpring Boot 4.xJDK 176.0.05.xSpring Boot 3.xJDK 175.0.04.3.xSpring Boot 2.xJDK 84.3.x从仓库根 pom.xml 可以看到 6.0.0 版本的关键依赖与编译约束maven.compiler.source/target均为 17jakarta.persistence-api版本为 3.2.0Jakarta JPA 注解mybatis版本为 3.5.19聚合模块mapper-modules下包含all、base、core、extra、spring、weekend、generator、spring-boot-starter、solon-plugin等子模块。引入 Maven 依赖在 Spring Boot 4.x / JDK 17 项目中使用 6.0.0直接在pom.xml中引入dependency groupIdtk.mybatis/groupId artifactIdmapper/artifactId version6.0.0/version /dependency该坐标对应 all/mapper 聚合产物内部整合了核心core、基础方法base、扩展方法extra与 Spring 集成spring等能力。若只需基础能力也可按需引入mapper-core、mapper-base、mapper-extra等独立坐标见 all/pom.xml 中的dependencyManagement声明。若使用 Spring Boot 2.x / JDK 8请选择 4.3.x 分支Spring Boot 3.x / JDK 17 请选择 5.x 分支。6.0 的核心变化JDK 17 Jakarta JPA 注解 Spring Boot 46.0 版本的技术栈底座发生了根本性变化README.md 对此说明如下基于JDK 17 Jakarta JPA 注解 Spring Boot 4配置完全兼容但实体类需要改用新版本的 JPA 注解jakarta.persistence.*如jakarta.persistence.Id、jakarta.persistence.Table同步更新copy了mybatis-spring 4.0.0与mybatis-spring-boot-starter 4.0.0此次更新主要是依赖的更新目标是适配最新的 Spring Boot 4.0.2提供更好的兼容性和稳定性。这一变化在仓库测试代码中有直接印证。例如 base 测试实体 Country 中主键注解已使用import jakarta.persistence.Id; public class Country implements Serializable { Id private Long id; private String countryname; private String countrycode; ... }如果你从旧版javax.persistence.*迁移需要同步替换实体类中的 JPA 注解包名业务配置代码则无需改动。快速上手第一个通用 Mapper参考 base 模块测试一个最小可用的通用 Mapper 只需三步。第一步定义实体类使用 JPA 注解标注主键与表映射表名、列名默认由实体类名/属性名按驼峰转下划线规则推导import jakarta.persistence.Id; public class Country implements Serializable { Id private Long id; private String countryname; private String countrycode; // getter / setter 省略 }第二步继承通用 Mapper 接口import tk.mybatis.mapper.common.Mapper; public interface CountryMapper extends MapperCountry { }CountryMapper本身是空接口但继承了 Mapper 后即获得一整套通用方法。查看源码可见其继承结构RegisterMapper public interface MapperT extends BaseMapperT, ExampleMapperT, RowBoundsMapperT, SaveMapperT, Marker { }而 BaseMapper 再聚合了查询、插入、更新、删除四组基础接口RegisterMapper public interface BaseMapperT extends BaseSelectMapperT, BaseInsertMapperT, BaseUpdateMapperT, BaseDeleteMapperT { }第三步注册扫描并在业务中使用在 MyBatis 配置中注册该 Mapperbase 测试 mybatis-config.xml 的注册方式mappers mapper classtk.mybatis.mapper.base.CountryMapper/ /mappers同时使用 MapperHelper 处理 Configuration通用 Mapper 会将ProviderSqlSource替换为真实 SQL测试基类 BaseTest 中mapperHelper.processConfiguration(...)即演示了非 Spring 环境下的接入方式。接入完成后即可直接调用通用方法CountryMapper mapper sqlSession.getMapper(CountryMapper.class); Country country mapper.selectByPrimaryKey(1L); // 按主键查询 mapper.insert(country); // 插入 mapper.updateByPrimaryKey(country); // 按主键更新 mapper.deleteByPrimaryKey(1L); // 按主键删除通用方法全景仓库 base 与 core 模块将通用方法按功能拆分为细粒度接口便于按需选择。从源码结构看主要分组如下分组接口代表方法基础查询SelectMapper、SelectByPrimaryKeyMapper、SelectAllMapper、SelectOneMapper、SelectCountMapper、ExistsWithPrimaryKeyMapperselect、selectByPrimaryKey、selectAll、selectOne、selectCount、existsWithPrimaryKey基础插入InsertMapper、InsertSelectiveMapperinsert、insertSelective基础更新UpdateByPrimaryKeyMapper、UpdateByPrimaryKeySelectiveMapperupdateByPrimaryKey、updateByPrimaryKeySelective基础删除DeleteByPrimaryKeyMapper、DeleteMapperdeleteByPrimaryKey、delete条件查询SelectByConditionMapper、SelectCountByConditionMapper、DeleteByConditionMapper、UpdateByConditionMapper、UpdateByConditionSelectiveMapperselectByCondition、selectCountByCondition等ExampleSelectByExampleMapper、SelectCountByExampleMapper、SelectOneByExampleMapper、DeleteByExampleMapper、UpdateByExampleMapper、UpdateByExampleSelectiveMapperselectByExample、deleteByExample等Ids 批量SelectByIdsMapper、DeleteByIdsMapperselectByIds、deleteByIdsRowBounds 分页SelectRowBoundsMapper、SelectByExampleRowBoundsMapper、SelectByConditionRowBoundsMapperselectByRowBounds等特殊InsertListMapper、InsertUseGeneratedKeysMapper批量插入、useGeneratedKeys插入SQL Server 方言SqlServerMapper下InsertMapper、InsertSelectiveMapperSQL Server 方言插入以 SelectByExampleMapper 为例每个方法通过 MyBatis 的SelectProvider注解绑定到 Provider 类SelectProvider(type ExampleProvider.class, method dynamicSQL) ListT selectByExample(Object example);dynamicSQL是 MapperTemplate 定义的占位方法真正的 SQL 由框架在启动阶段生成并替换。组合接口按需拼装仓库提供了多种预置组合接口避免逐一继承细粒度接口BaseMapperT基础增删改查MapperTBaseMapper ExampleMapper RowBoundsMapper SaveMapperMySqlMapperT追加 MySQL 相关方法如批量插入SqlServerMapperT、ConditionMapperT、ExampleMapperT、IdsMapperT、SaveMapperT等。这些接口统一标注了RegisterMapper见 RegisterMapper.java会被 MapperHelper 自动识别注册。深入原理SQL 是如何自动生成的通用 Mapper 的核心类是 MapperHelper其注释直接标明处理主要逻辑最关键的一个类。关键链路如下注册通用接口registerMapper(Class?)遍历接口中声明的方法读取方法上的SelectProvider/InsertProvider/DeleteProvider/UpdateProvider注解找到对应的 Provider 模板类并通过反射实例化 MapperTemplate 子类如BaseSelectProvider、ExampleProvider。若注解缺失或模板类非法则回退到EmptyProvider。方法注册addMethodMap(methodName, method)将每个通用方法名绑定到模板类中同名方法供后续 SQL 生成调用。自动注册继承接口registerMapper会递归注册当前接口的所有父接口因此CountryMapper extends MapperT时Mapper、BaseMapper以及更细粒度的接口会被依次注册。处理 MappedStatementprocessConfiguration(Configuration)遍历 MyBatisConfiguration中全部MappedStatement对命中的通用方法调用setSqlSource将占位ProviderSqlSource替换为基于 XML 动态 SQLXMLLanguageDriver构建的真实SqlSource——参见 MapperTemplate.createSqlSource。实体解析SQL 生成依赖 EntityHelper 与 DefaultEntityResolve 解析实体类注解得到表名、列名、主键、属性映射等元数据缓存为EntityTable。通过RegisterMapper注解框架还支持继承的通用接口自动注册hasRegisterMapper递归检查父接口这正是细粒度接口组合能力的来源。全局配置详解通用 Mapper 的全部可配置项集中定义在 Config.java前缀为mapperPREFIX mapper。以下参数均可在application.properties/application.yml中通过mapper.xxx配置配置项默认值说明mappers空Spring Boot 下自动注册tk.mybatis.mapper.common.Mapper逗号分隔的通用 Mapper 接口全限定类名列表IDENTITY/identityMySQL主键自增回写 SQL支持IdentityDialect内置方言如 MYSQL也可自定义order/beforeAFTERSelectKey 回写主键的执行顺序BEFORE或AFTERseqFormat{0}.nextval序列获取规则{0}为 SequenceName针对 Oraclecatalog空全局 catalog设置后 SQL 形如catalog.tablenameschema空全局 schema与 catalog 同时设置时优先 catalogstylecamelhump字段名转换风格驼峰转下划线camelhump、normal、uppercase、lowercase等非法值会抛出MapperExceptionnotEmptyfalse对getAllIfColumnNode是否额外判断! useSimpleTypetrue3.5.0 后是否使用简单类型enumAsSimpleTypefalse枚举是否作为简单类型处理simpleTypes空注册新的基本类型逗号分隔全限定类名usePrimitiveTypefalse是否注册 8 种 Java 基本类型enableMethodAnnotationfalse是否支持方法上的注解checkExampleEntityClassfalse校验调用 Example 方法时Example(entityClass)与MapperEntityClass是否一致wrapKeyword空关键字包装mysql 可设为{0}sqlserver 可设为[{0}]{0}代表列名resolveClass空自定义实体解析器EntityResolve实现类safeDeletefalse安全删除开启后不允许无条件的全表删除如delete from tablesafeUpdatefalse安全更新开启后不允许无条件的全表更新logicDeleteByKeytrue通过主键进行 select/update/delete 时是否拼接逻辑删除条件设为 false 时不追加logicDeleteField 0useJavaTypefalse是否在 SQL 参数中设置 javaType如{id, javaTypejava.lang.Long}enableBaseResultMapFlagfalse是否自动把 Mapper 接口中手写指定 resultType 的查询结果改为 resultMap这些参数的解析逻辑均可在 Config.setProperties 中找到例如IDENTITY会先尝试通过IdentityDialect.getDatabaseDialect识别内置方言识别失败则按自定义 SQL 处理style非法时直接抛出异常。Spring Boot 集成仓库 spring-boot-starter 模块提供了mapper-spring-boot-starter与mapper-spring-boot-autoconfigure。其中 MapperProperties 直接继承Config并标注ConfigurationProperties(prefix mapper)其设计目的见类注释就是方便 IDE 自动提示mapper.开头的配置# 显式注册通用 Mapper 接口不配置时默认自动注册 tk.mybatis.mapper.common.Mapper mapper.mappers[0]tk.mybatis.mapper.common.Mapper # 全局配置示例 mapper.stylecamelhump mapper.safeDeletetrue mapper.wrapKeyword{0}MapperAutoConfiguration 负责自动装配SqlSessionFactory与SqlSessionTemplate并在初始化阶段将MapperProperties绑定到MapperHelper。在 Spring Boot 项目中通常只需引入mapper-spring-boot-starter实体类与 Mapper 接口同上接口继承tk.mybatis.mapper.common.Mapper或自定义组合在启动类或配置类上使用tk.mybatis.spring.annotation.MapperScan扫描 Mapper 接口注意使用 tk 包下的注解而非 MyBatis 官方注解。需要说明的是仓库中spring-boot-starter模块 READMEspring-boot-starter/README.md展示的是较早期版本1.2.x的集成文档其核心接入方式starter 依赖 mapper.前缀配置 tk 包MapperScan在当前版本中依然成立但版本配套请以本文前述的版本匹配说明为准。高级特性主键策略KeySqlKeySql 用于替换 JPA 中复杂的主键生成用法支持四种策略按优先级从高到低useGeneratedKeys()使用 JDBC 方式获取主键优先级最高设为 true 后不再校验其他配置dialect()按配置的数据库方言取回主键IdentityDialect优先级第二sql()/genSql()自定义取主键 SQL或通过GenSql在初始化时生成 SQLgenId()纯 Java 方式生成主键GenId实现类可与发号器一类服务配合。order()默认使用全局配置中的ORDERBEFORE/AFTER。仓库测试 base/genid 提供了SimpleGenId、UUIdGenId等实现示例。逻辑删除LogicDeleteLogicDelete 支持字段级逻辑删除属性包括isDeletedValue()已删除标识默认 1notDeletedValue()未删除标识默认 0isNullForDeletedValue()以 null 作为已删除标识优先级高于isDeletedValueisNullForNotDeletedValue()以 null 作为未删除标识优先级高于notDeletedValue。配合全局配置mapper.logicDeleteByKeytrue默认通过主键的 select/update/delete 会自动拼接逻辑删除条件。安全删除与安全更新开启mapper.safeDeletetrue后框架禁止无条件全表删除。仓库测试 SafeDeleteByFieldTest 验证了四种危险场景都会抛出PersistenceExceptiondelete(new Country())空条件对象delete(null)deleteByExample(new Example(Country.class))空 ExampledeleteByExample(null)。同理mapper.safeUpdatetrue保护全表更新对应测试见 SafeUpdateByFieldTest。Example 条件查询Example 是通用 Mapper 内置的条件查询对象支持orderBy、selectProperties/excludeProperties指定/排除查询列、and()/or()分组条件、distinct、forUpdate等。其构造函数Example(Class? entityClass)默认existstrue也可使用Example.builder(entityClass)链式构建配合 Sqls 工具类生成orderBy、select等子句。配合 Weekend 模块还可以用 Lambda 方式WeekendSqls书写类型安全的条件避免字符串属性名拼写错误。扩展方法extra 模块extra 模块提供更多实用通用方法extra/README.md 有介绍批量插入tk.mybatis.mapper.additional.insert.InsertListMapperSQL 形如insert table(xxx) values (xxx), (xxx)...适用于 MySQL、H2 等支持多值插入的数据库Oracle 特殊批量插入使用INSERT ALL ... SELECT 1 FROM DUAL语法见additional.dialect.oracle.InsertListMapper由于语法限制暂不支持序列空字段强制更新UpdateByPrimaryKeySelectiveForceMapper解决UpdateByPrimaryKeySelective场景下空值也需要被设置的需求按属性查询/删除SelectByPropertyMapper、DeleteByPropertyMapper按 Id 列表操作SelectByIdListMapper、DeleteByIdListMapper指定列查询SelectSpecifyColumnsMapper批量更新 / 差异更新 / UpsertBatchUpdateMapper、UpdateByDifferMapper、UpsertMapper等聚合查询AggregationMapper配合AggregateCondition实现分组聚合。设计你自己的通用方法仓库 README 特别强调不要局限于已有通用方法根据自己需要选择和设计的通用方法才更满足自己的需要。结合源码自定义通用方法的标准路径是定义细粒度接口并标注RegisterMapper方法上绑定自定义 Provider例如RegisterMapper public interface MySelectMapperT { SelectProvider(type MyProvider.class, method dynamicSQL) T mySelect(T record); }继承 MapperTemplate 编写 Provider利用EntityHelper获取实体元数据用createSqlSource(ms, xmlSql)生成动态 SQL其中模板方法签名需与接口方法一一对应MapperHelper.fromMapperClasses会通过templateClass.getMethod(method.getName(), MappedStatement.class)校验缺失会抛出异常。将自定义接口注册进Config.mappers或通过RegisterMapper自动注册即可像内置方法一样被 MapperHelper 拦截并替换 SQL。仓库 hsqldb/HsqldbProvider 与 MultipleMapperProviderTest 都是自定义 Provider 的现成参考。新项目建议对于全新项目README.md 建议关注新一代的mybatis-mapper它完全作为 MyBatis 扩展存在不修改 mybatis、mybatis-spring、mybatis-spring-boot-starter 任何代码无需额外配置可快速上手。若项目仍需停留在 Spring Boot 2.x / JDK 8 或 3.x / JDK 17则按版本匹配说明选择 4.3.x 或 5.x 分支的通用 Mapper。参考资源仓库根 README.md版本匹配说明、Maven 坐标与更新说明core 模块Config.java、MapperHelper.java、Example.java、注解包 annotationbase 模块通用接口 common、Provider 实现 provider以及 base 测试集实体、Mapper、HSQLDB 建表脚本 CreateDB.sqlextra 模块扩展通用方法及其测试spring-boot-starter 模块自动配置与mapper.前缀属性绑定weekend 模块Lambda 类型安全的条件查询封装。赞分享后端ORM数据库【免费下载链接】MapperMybatis Common Mapper - Easy to use项目地址https://gitcode.com/gh_mirrors/ma/Mapper点击查看免费下载相关推荐Spring Boot数据持久化完全指南JPA、MyBatis与MyBatis-Plus对比Spring Boot数据持久化完全指南JPA、MyBatis与MyBatis Plus对比 在Spring Boot应用开发中 数据持久化 是构建健壮企业示例工程后端5 分钟上手 FreeCAD免费 3D 参数化建模 CAD从一张草图到能交付的零件5 分钟上手 FreeCAD免费 3D 参数化建模 CAD从一张草图到能交付的零件 想给桌上那台设备配一个严丝合缝的定制支架或者打个能正好卡进某个凹槽的桌面应用3D建模图形学工业制造3小时快速上手Mybatis Common Mapper与Spring Boot的终极集成指南3小时快速上手Mybatis Common Mapper与Spring Boot的终极集成指南 还在为Mybatis繁琐的配置而头疼想要在Spring Bo后端ORM数据库创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑