当前位置:   article > 正文

Mybatis多表映射之一对多映射

Mybatis多表映射之一对多映射

上文总结了一对一关联关系中的映射方法。那么,如果存在一对多关系,又该定义映射关系呢?

1. 需求说明

假设目前存在顾客表与订单表,一个顾客与多个订单对应。因此,在顾客实体类中,应该有一个订单类型的list列表。如下所示:

public class Customer {

  private Integer customerId;
  private String customerName;
  private List<Order> orderList;// 体现的是对多的关系
}

public class Order {

  private Integer orderId;
  private String orderName;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2. CustomerMapper接口

定义一个方法接口,根据顾客id查询顾客信息及对应的订单信息。

public interface CustomerMapper {

  Customer selectCustomerWithOrderList(Integer customerId);

}
  • 1
  • 2
  • 3
  • 4
  • 5

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_name
  FROM t_customer c
  LEFT JOIN t_order o
  ON c.customer_id=o.customer_id
  WHERE c.customer_id=#{customerId}
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

总结:

  • 一对多映射时,在resultMap中使用标签collection
  • 与一对一映射中association一样,property属性值为被关联的实体类属性名相同。在上述例子中,顾客类中订单类型的集合属性名为orderList。
  • ofType与association中的javaType一样,属性值为被关联的实体类的全类名。这里是list列表,因此填列表的泛型类型,也就是订单类。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/251672
推荐阅读
相关标签
  

闽ICP备14008679号