mybatis0205 一对多查询 复杂
查询所有用户信息,关联查询订单及订单明细信息及商品信息,订单明细信息中关联查询商品信息
1.1sql 主查询表:用户信息 关联查询:订单、订单明细,商品信息 SELECT orders.*, user.username, user.sex , orderdetail.id orderdetail_id, orderdetail.items_num, orderdetail.items_id, items.name items_name, items.detail items_detail FROM orders, USER, orderdetail, items WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id AND items.id = orderdetail.items_id
pojo定义 在user.java(主表)中创建映射的属性:集合 List<Orders> orderlist 在Orders中创建映射的属性:集合List<Orderdetail> orderdetails 在Orderdetail中创建商品属性:pojo Items items
mapper.xml
<!-- 一对多查询使用reusltMap完成 查询用户及订单和订单明细,关联商品,的信息 --> <select id="findUserOrderDetail" resultMap="userOrderDetailResultMap" > SELECT orders.*, user.username, user.sex , orderdetail.id orderdetail_id, orderdetail.items_num, orderdetail.items_id, items.name items_name, items.detail items_detail FROM orders, USER, orderdetail, items WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id AND items.id = orderdetail.items_id </select>
将查询的数据库结果和User接收对象进行映射
<!-- 一对多查询,查询用户及订单明细和商品信息 --> <resultMap type="user" id="userOrderDetailResultMap"> <!-- 用户信息User映射 --> <id column="user_id" property="id"/>id是User的属性,user_id是查询的数据库表的列名 <result column="username" property="username"/> <result column="sex" property="sex"/> <!-- 订单信息,orderlist是User的属性 --> <collection property="orderlist" ofType="cn.itcast.mybatis.po.Orders"> <id column="id" property="id"/>id是Orders的属性,id是查询的数据库表的列名 <result column="user_id" property="userId"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <!-- 订单明细映射 --> <collection property="orderdetails" ofType="cn.itcast.mybatis.po.Orderdetail"> <!-- id:关联信息订单明细的唯 一标识 property:Orderdetail的属性名 --> <id column="orderdetail_id" property="id"/> <result column="items_num" property="itemsNum"/> <result column="items_id" property="itemsId"/> <!-- 商品信息 --> <association property="items" javaType="cn.itcast.mybatis.po.Items"> <id column="item_id" property="id"/> <result column="items_name" property="name"/> <result column="items_detail" property="detail"/> </association> </collection> </collection> </resultMap>
1.1 mapper.java
测试:
// 一对多查询使用resultMap @Test public void testFindUserOrderDetail() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); // 创建mapper代理对象 OrdersMapperCustom ordersMapperCustom = sqlSession .getMapper(OrdersMapperCustom.class); // 调用方法 List<User> list = ordersMapperCustom.findUserOrderDetail(); System.out.println(list); }