1.需求
查詢用戶及用戶購買商品信息
2.思路
- 將用戶信息映射到user中蒋譬。
- 在UserBean類中添加訂單列表屬性List<OrdersBean> ordersBean,將用戶創(chuàng)建的訂單映射到ordersBean愉适。
- 在OdersBean中添加訂單明細列表屬性List<OrderDetailBean> orderDetailBeans犯助,將訂單的明細映射到orderDetailBeans。
- 在OrderDetail中添加items屬性ItemsBean itemsBean维咸,將訂單明細所對應(yīng)的商品映射到itemsBean剂买。
3.實現(xiàn)
(1)配置映射
(2)配置文件
OrdersMapperCustom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.OrdersMapperCustom">
<!--查詢用戶及用戶購買商品信息-->
<resultMap id="UserAndItemsResultMap" type="entity.UserBean">
<!--用戶信息-->
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
<!--訂單信息-->
<collection property="ordersBeans" ofType="entity.OrdersBean">
<id column="id" property="id"></id>
<result column="user_id" property="user_id"></result>
<result column="number" property="number"></result>
<result column="createtime" property="createtime"></result>
<result column="note" property="note"></result>
<!--訂單明細-->
<collection property="orderdetailBeans" ofType="entity.OrderdetailBean">
<id column="orderdetail_id" property="id"></id>
<result column="items_id" property="orders_id"></result>
<result column="items_id" property="items_id"></result>
<result column="orders_id" property="orders_id"></result>
<!--商品信息-->
<association property="itemsBean" javaType="entity.ItemsBean">
<id column="items_id" property="id"></id>
<result column="items_name" property="name"></result>
<result column="items_detail" property="detail"></result>
<result column="items_price" property="price"></result>
</association>
</collection>
</collection>
</resultMap>
<!--查詢用戶及用戶購買商品信息-->
<select id="findUserAndItemsResultMap" resultMap="UserAndItemsResultMap">
SELECT
orders.*,
user.username,
user.sex,
user.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.item_num,
orderdetail.orders_id,
items.name items_name,
items.detail items_detail,
items.price items_price
FROM
orders,
USER,
orderdetail,
items
WHERE
orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id
</select>
</mapper>
(3)OrdersMapperCustom.java
接口
public List<UserBean> findUserAndItemsResultMap() throws Exception;
(4)測試
@Test
public void findUserAndItemsResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
List<UserBean> userBeans = ordersMapperCustom.findUserAndItemsResultMap();
System.out.println(userBeans);
}