mybatis中用实现一对一关联,核心是将主表结果与关联表单条记录映射到java对象的两个属性上;需合理设计实体类、配置映射规则,支持嵌套结果映射和嵌套查询两种方式,并注意n+1问题及常用属性配置。

MyBatis 中用 <association></association> 实现一对一关联,核心是把“主表结果”和“关联表单条记录”映射到一个 Java 对象的两个属性上,关键在于配置好映射规则和查询方式。
明确关联关系与 Java 类结构
先确保实体类设计合理。比如订单(Order)和用户(User)是一对一关系,Order 类中应有 User user 属性,且字段名、类型与数据库和 SQL 结果一致。
-
Order表含user_id字段,指向User表主键 -
User类需有id、name等对应字段 - 避免使用驼峰命名冲突,必要时开启
mapUnderscoreToCamelCase=true
写法一:嵌套结果映射(推荐用于简单场景)
用 <resultmap></resultmap> 内部嵌套 <association></association>,通过列别名或 columnPrefix 区分字段,一次性查出所有数据。
<resultmap id="OrderWithUserResultMap" type="Order"><id property="id" column="order_id"></id><result property="orderNo" column="order_no"></result><association property="user" javatype="User"><id property="id" column="user_id"></id><result property="name" column="user_name"></result><result property="email" column="user_email"></result></association></resultmap><select id="selectOrderWithUser" resultmap="OrderWithUserResultMap">
SELECT
o.id AS order_id,
o.order_no,
u.id AS user_id,
u.name AS user_name,
u.email AS user_email
FROM `order` o
LEFT JOIN user u ON o.user_id = u.id
WHERE o.id = #{id}
</select>
注意列别名必须唯一,且 <association></association> 内的 property 是 User 的字段,column 是 SQL 返回的别名。
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
写法二:嵌套查询(适合复用或复杂逻辑)
让 MyBatis 先查主表,再根据外键字段调用另一个 SQL 查询关联对象,用 select 属性指定语句 ID,column 指定传参字段。
<resultmap id="OrderWithUserBySelectResultMap" type="Order"><id property="id" column="id"></id><result property="orderNo" column="order_no"></result><association property="user" javatype="User" select="selectUserById" column="user_id"></association></resultmap><select id="selectOrderWithUserBySelect" resultmap="OrderWithUserBySelectResultMap">
SELECT id, order_no, user_id FROM `order` WHERE id = #{id}
</select><select id="selectUserById" resulttype="User">
SELECT id, name, email FROM user WHERE id = #{id}
</select>
这种方式会触发 N+1 查询问题,建议配合 <cache></cache> 或延迟加载(fetchType="lazy")优化。
常用配置细节不能漏
<association></association> 支持多个关键属性,按需设置:
-
property:主对象中关联对象的属性名(如user) -
javaType:关联对象完整类名或别名(必须,不能省略) -
resultMap:可复用已定义的<resultmap></resultmap>,比写一堆<result></result>更清晰 -
columnPrefix:当关联字段统一加前缀(如u_),可在<association></association>内统一处理 -
notNullColumn:指定某列为非空时才实例化关联对象(避免 null 值创建空对象)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










