标签:
查询所有订单信息及订单下的订单明细信息。
sql语句 主查询表:订单表 关联查询表:订单明细 SELECT orders.*, user.username, user.sex , orderdetail.id orderdetail_id, orderdetail.items_num, orderdetail.items_id FROM orders, USER, orderdetail WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id
1.1resultMap进行一对多映射思路
resultMap 提供collection完成关联信息映射到集合对象中。
在orders类中创建集合属性:
<select id="findOrderAndOrderDetails" resultMap="orderAndOrderDetails" > SELECT orders.*, user.username, user.sex , orderdetail.id orderdetail_id, orderdetail.items_num, orderdetail.items_id FROM orders, USER, orderdetail WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id </select>
<!-- 一对多,查询订单及订单明细 --> <!-- type="orders"为返回值类型, --> <resultMap type="orders" id="orderAndOrderDetails" extends="ordersUserResultMap"> <!-- 映射订单信息,和用户信息,这里使用继承ordersUserResultMap --> <!-- 映射订单明细信息 property:要将关联信息映射到orders的哪个属性中 ofType:集合中pojo的类型 --> <collection property="orderdetails" ofType="cn.itcast.mybatis.po.Orderdetail"> <!-- id:关联信息订单明细Orderdetail的唯 一标识 property:Orderdetail的属性名 --> <id column="orderdetail_id" property="id"/> id为Orderdetail的id属性 <result column="items_num" property="itemsNum"/> <result column="items_id" property="itemsId"/> </collection> </resultMap>
<resultMap type="orders" id="ordersUserResultMap"> <!-- 完成了订单信息Order的映射配置 --> <id column="id" property="id"/> <!-- Orders的id,整个查询的唯一标识就是Orders的id --> <result column="user_id" property="userId"/><!-- Orders的userId--> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <!-- 下边完成关联信息User的映射 association:用于对关联信息User映射到单个pojo(Orders) property:要将关联信息映射到orders的哪个属性中 javaType:关联信息映射到orders的属性的类型,是user的类型 --> <association property="user" javaType="user"> <!-- id:关联信息User的唯 一标识 --> <!-- property: 要映射到user的哪个属性中--> <id column="user_id" property="id"/>id为User的id <!-- result就是普通列的映射 --> <result column="username" property="username"/> <result column="sex" property="sex"/> </association> </resultMap>
测试:
// 一对多查询使用resultMap @Test public void testFindOrderAndOrderDetails() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); // 创建mapper代理对象 OrdersMapperCustom ordersMapperCustom = sqlSession .getMapper(OrdersMapperCustom.class); // 调用方法 List<Orders> list = ordersMapperCustom.findOrderAndOrderDetails(); System.out.println(list); }
User.java
public class User implements Serializable { private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址
Orderdetail.java
public class Orderdetail implements Serializable { private Integer id; private Integer ordersId; private Integer itemsId; private Integer itemsNum; //商品信息 private Items items;
标签:
原文地址:http://www.cnblogs.com/yaowen/p/4872726.html