标签:
需求:查询订单及订单明细的信息
1.写sql语句
确定主查询表:订单表
确定关联查询表:订单明细表
在一对一的基础之上,添加订单明细表关联即可,同时,对orders映射不能出现重复记录
select
orders.*,
user.username,
user.sex,
user.address,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id
from
orders, user, orderdetail
where orders.user_id = user.id and orderdetail.orders_id = orders.id
在orders.java类中添加List<orderDetail> orderDetails属性,
最终会将订单信息映射到orders中,订单所对应的订单明细映射到orders中的orderDetails属性中。
2.写mapper.xml
<resultMap type="po.Orders" id="OrdersAndOrderDetailResultMap" extends="OrdersUserResultMap">
<collection property="orderdetails" ofType="po.Orderdetail">
<id column="orderdetail_id" property="id"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<result column="orders_id" property="ordersId"/>
</collection>
</resultMap>
<select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">
SELECT
orders.*,
USER.username,
USER.sex,
USER.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id
FROM
orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id
</select>
3.写mapper.java
4.写测试,测试成功
@Test
public void testFindOrdersAndOrderDetailResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersCustomMapper ordersCustomMapper = sqlSession
.getMapper(OrdersCustomMapper.class);
List<Orders> list = ordersCustomMapper
.findOrdersAndOrderDetailResultMap();
System.out.println(list);
sqlSession.close();
}
5.小结
mybatis使用resultMap的collection对关联查询的多条记录映射到一个list集合属性中。
使用resultType实现:
将订单明细映射到orders中的orderdetails中,需要自己处理,使用双重循环遍历,去掉重复记录,将订单明细放在orderdetails中。
标签:
原文地址:http://www.cnblogs.com/hqt2050/p/4986140.html