一、一对多
举个例子讲个痛快:查一个订单对应的多个订单项
贴出了重要代码,OrderMapper.xml
<!-- 一对多的关系 -->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<resultMap id="OrderMap" type="com.zking.ssm.model.Order">
<result property="orderId" column="order_id"></result>
<result property="orderNo" column="order_no"></result>
<collection property="orderItems" ofType="com.zking.ssm.model.OrderItem">
<result property="orderItemId" column="order_item_id"></result>
<result property="productId" column="product_id"></result>
<result property="quantity" column="quantity"></result>
<result property="oid" column="oid"></result>
</collection>
</resultMap>
写SQL语句时要注意 使用左外连接而非内连接!!!
<select id="queryOrderById" resultMap="OrderMap" parameterType="java.lang.Integer">
select * from t_hibernate_order o,t_hibernate_order_item oi
where o.order_id= oi.oid
and o.order_id = #{orderId}
</select>
测试
@Autowired
private OrderService orderService;
@Test
public void queryOrderById() {
List<Order> orders = orderService.queryOrderById(3);
for (Order order : orders) {
System.out.println(order);
}
}
二、多对一
多个订单项对应的订单
<!-- 多对一的关系 -->
<!-- property: 指的是属性的值, javaType:指的是属性的类型-->
<resultMap id="OrderItemMap" type="com.zking.ssm.model.OrderItem">
<result property="orderItemId" column="order_item_id"></result>
<result property="productId" column="product_id"></result>
<result property="quantity" column="quantity"></result>
<result property="oid" column="oid"></result>
<association property="orders" javaType="com.zking.ssm.model.Order">
<result property="orderId" column="order_id"></result>
<result property="orderNo" column="order_no"></result>
</association>
</resultMap>
<select id="queryOrderItemById" resultMap="OrderItemMap" parameterType="java.lang.Integer">
select * from t_hibernate_order o,t_hibernate_order_item oi
where o.order_id= oi.oid
and oi.order_item_id = #{orderId}
</select>
测试:
@Autowired
private OrderItemService orderItemService;
@Test
public void queryOrderItemById() {
OrderItem orderItem = orderItemService.queryOrderItemById(3);
System.out.println(orderItem);
}
三、多对多
扫描二维码关注公众号,回复:
5249341 查看本文章
多对多相当于两个一对多,同上面的例子一样。
注意:
一对多用ofType,多对一用JavaType。