上文总结了一对一关联关系中的映射方法。那么,如果存在一对多关系,又该定义映射关系呢?
1. 需求说明
假设目前存在顾客表与订单表,一个顾客与多个订单对应。因此,在顾客实体类中,应该有一个订单类型的list列表。如下所示:
public class Customer {private Integer customerId;private String customerName;private List<Order> orderList;// 体现的是对多的关系
}public class Order {private Integer orderId;private String orderName;
}
2. CustomerMapper接口
定义一个方法接口,根据顾客id查询顾客信息及对应的订单信息。
public interface CustomerMapper {Customer selectCustomerWithOrderList(Integer customerId);}
3. CustomerMapper.xml文件
<!-- 配置resultMap实现从Customer到OrderList的“对多”关联关系 -->
<resultMap id="selectCustomerWithOrderListResultMap" type="customer"><!-- 映射Customer本身的属性 --><id column="customer_id" property="customerId"/><result column="customer_name" property="customerName"/><!-- collection标签:映射“对多”的关联关系 --><!-- property属性:在Customer类中,关联“多”的一端的属性名 --><!-- ofType属性:集合属性中元素的类型 --><collection property="orderList" ofType="order"><!-- 映射Order的属性 --><id column="order_id" property="orderId"/><result column="order_name" property="orderName"/></collection></resultMap><!-- Customer selectCustomerWithOrderList(Integer customerId); -->
<select id="selectCustomerWithOrderList" resultMap="selectCustomerWithOrderListResultMap">SELECT c.customer_id,c.customer_name,o.order_id,o.order_nameFROM t_customer cLEFT JOIN t_order oON c.customer_id=o.customer_idWHERE c.customer_id=#{customerId}
</select>
总结:
- 一对多映射时,在resultMap中使用标签collection
- 与一对一映射中association一样,property属性值为被关联的实体类属性名相同。在上述例子中,顾客类中订单类型的集合属性名为orderList。
- ofType与association中的javaType一样,属性值为被关联的实体类的全类名。这里是list列表,因此填列表的泛型类型,也就是订单类。