赞
踩
上文总结了一对一关联关系中的映射方法。那么,如果存在一对多关系,又该定义映射关系呢?
假设目前存在顾客表与订单表,一个顾客与多个订单对应。因此,在顾客实体类中,应该有一个订单类型的list列表。如下所示:
public class Customer {
private Integer customerId;
private String customerName;
private List<Order> orderList;// 体现的是对多的关系
}
public class Order {
private Integer orderId;
private String orderName;
}
定义一个方法接口,根据顾客id查询顾客信息及对应的订单信息。
public interface CustomerMapper {
Customer selectCustomerWithOrderList(Integer customerId);
}
<!-- 配置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_name FROM t_customer c LEFT JOIN t_order o ON c.customer_id=o.customer_id WHERE c.customer_id=#{customerId} </select>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。