在 MyBatis 中,<association> 和 <collection> 是用于配置结果映射中关联关系的两个元素。
<association> 用于配置一对一的关联关系,表示两个对象之间的关系是一对一的。例如,一个订单对象关联一个用户对象,使用 <association> 进行配置。
<collection> 用于配置一对多的关联关系,表示一个对象关联多个对象。例如,一个部门对象关联多个员工对象,使用 <collection> 进行配置。
主要区别:
-
关联关系类型:
<association>表示一对一的关联关系,而<collection>表示一对多的关联关系。 -
配置位置:
<association>和<collection>元素通常在<resultMap>中使用,用于定义结果映射规则。<association>用于配置单个属性的关联关系,而<collection>用于配置集合属性的关联关系。 -
属性映射:
<association>使用<id>和<result>进行属性映射的配置,用于将关联对象的属性与查询结果进行映射。<collection>除了使用<id>和<result>进行属性映射外,还使用<association>进行嵌套的关联关系配置,用于定义集合元素对象内部的关联关系。 -
查询语句:
<association>通常对应一个单独的查询语句,用于获取关联对象的数据。<collection>通常也对应一个查询语句,用于获取关联对象的集合数据。
示例:
下面是一个示例的 Java 实体类,用于表示订单(Order)、用户(User)和订单项(OrderItem)的关系:
public class Order {private int orderId;private String orderNumber;private User user;private List<OrderItem> orderItems;}public class User {private int userId;private String username;}public class OrderItem {private int orderItemId;private String itemName;private int quantity;}
在上述示例中,Order 类表示订单,包含了订单的基本信息(orderId 和 orderNumber),以及关联的用户对象(user)和订单项对象集合(orderItems)。
User 类表示用户,包含了用户的基本信息(userId 和 username)。
OrderItem 类表示订单项,包含了订单项的基本信息(orderItemId、itemName 和 quantity)。
xml配置:
当使用 MyBatis 的 XML 配置文件进行结果映射时,以下是 <association> 和 <collection> 元素的示例配置:
<resultMap id="orderResultMap" type="Order"><id property="orderId" column="order_id" /><result property="orderNumber" column="order_number" /><association property="user" javaType="User"><id property="userId" column="user_id" /><result property="username" column="username" /></association><collection property="orderItems" ofType="OrderItem"><id property="orderItemId" column="item_id" /><result property="itemName" column="item_name" /><result property="quantity" column="quantity" /></collection>
</resultMap><select id="getOrderById" resultMap="orderResultMap">SELECT * FROM orders WHERE order_id = #{orderId}</select>
使用 <association> 配置了 user 属性的关联关系。property 属性指定了关联属性的名称为 user,javaType 属性指定了关联属性的类型为 User。在 <association> 元素内部,使用 <id> 和 <result> 元素进行属性映射的配置。
使用 <collection> 配置了 orderItems 属性的关联关系。property 属性指定了关联属性的名称为 orderItems,ofType 属性指定了集合元素的类型为 OrderItem。在 <collection> 元素内部,同样使用 <id> 和 <result> 元素进行属性映射的配置。