全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 6 分钟 ✍️ juanwangdev

一对一关联映射

association 元素用于处理一对一关联关系,将关联对象映射到主对象的属性中。

association 基本用法

XML
<resultMap id="employeeResultMap" type="Employee">
  <id property="id" column="emp_id"/>
  <result property="name" column="emp_name"/>
  <association property="department" javaType="Department">
    <id property="id" column="dept_id"/>
    <result property="name" column="dept_name"/>
  </association>
</resultMap>
属性说明
property关联属性名
javaType关联对象类型
resultMap引用外部已定义的 resultMap
columnPrefix列名前缀,避免列名冲突

嵌套结果映射(Join 方式)

通过一条 SQL JOIN 查询获取关联数据:

Java
public class Employee {
  private Integer id;
  private String name;
  private Department department;
}

public class Department {
  private Integer id;
  private String name;
}
XML
<resultMap id="empDeptResultMap" type="Employee">
  <id property="id" column="emp_id"/>
  <result property="name" column="emp_name"/>
  <association property="department" javaType="Department">
    <id property="id" column="dept_id"/>
    <result property="name" column="dept_name"/>
  </association>
</resultMap>

<select id="selectEmployeeWithDept" resultMap="empDeptResultMap">
  SELECT e.id emp_id, e.name emp_name,
         d.id dept_id, d.name dept_name
  FROM employee e
  LEFT JOIN department d ON e.dept_id = d.id
  WHERE e.id = #{id}
</select>

JOIN 方式一次查询完成,性能优于子查询,但需注意列别名避免冲突。

子查询方式(N+1 模式)

XML
<resultMap id="employeeResultMap" type="Employee">
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  <association property="department"
               column="dept_id"
               javaType="Department"
               select="selectDepartment"/>
</resultMap>

<select id="selectEmployee" resultMap="employeeResultMap">
  SELECT * FROM employee WHERE id = #{id}
</select>

<select id="selectDepartment" resultType="Department">
  SELECT * FROM department WHERE id = #{id}
</select>

子查询 vs Join 对比

维度Join 方式子查询方式
SQL 数量1 条N+1 条(N 为主表记录数)
性能高,单次查询低,多次查询
灵活性列名需别名避免冲突映射简单
适用场景一对一、一对多按需加载、复杂关联
N+1 问题存在

一对一关联优先使用 Join 方式;若需延迟加载,则使用子查询方式配合懒加载配置。

引用外部 resultMap

关联对象映射规则复杂时,可独立定义 resultMap 再引用:

XML
<resultMap id="departmentResult" type="Department">
  <id property="id" column="dept_id"/>
  <result property="name" column="dept_name"/>
  <result property="location" column="dept_location"/>
</resultMap>

<resultMap id="employeeResultMap" type="Employee">
  <id property="id" column="emp_id"/>
  <result property="name" column="emp_name"/>
  <association property="department"
               resultMap="departmentResult"
               columnPrefix="dept_"/>
</resultMap>

columnPrefix 属性可自动为关联 resultMap 中所有列添加前缀,简化 JOIN 查询的列别名配置。

要点总结

  • association 用于一对一关联映射。
  • Join 方式性能更优,一次查询获取所有数据。
  • 子查询方式灵活,但存在 N+1 问题。
  • 可引用外部 resultMap 实现映射复用。
  • columnPrefix 简化 JOIN 列别名配置。

📝 发现内容有误?点击此处直接编辑

← 上一篇 discriminator 鉴别器
下一篇 → 一对多集合映射
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库