使用四张表完成多对多的建立关系
用户表
订单表
订单明细表
商品表
实体类
User`
private Integer id;
private String name;
private String sex;
//商品订单
public List<Orders> orders;
Orders
private Integer o_id;
private String o_name;
private Integer u_id;
//用户表
private User user;
//订单明细表
private List<OrdersDemo> ordersDemos;
OrdersDemo //订单明细表
private Integer d_id;
private Integer d_num;
private Integer d_price;
private Integer orders_id;
//商品信息
private Item item;
Item //商品信息表
private Integer i_id;
private String i_text;
private Integer i_price;
private String i_dec; //商品描述信息
userMapper.xml
<mapper namespace="com.zhou.mapper.UserMapper">
<resultMap id="userItemFindAllResultMap" type="com.zhou.bean.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<!-- 一个商品订单有多个商品信息-->
<collection property="orders" ofType="com.zhou.bean.Orders">
<id column="o_id" property="o_id"/>
<result column="o_name" property="o_name"/>
<result column="u_id" property="u_id"/>
<!-- 一个商品订单男有多个商品信息-->
<collection property="ordersDemos" ofType="com.zhou.bean.OrdersDemo">
<id column="d_id" property="d_id"/>
<result column="d_num" property="d_num"/>
<result column="d_price" property="d_price"/>
<result column="order_id" property="order_id"/>
<!--一个订单详细 有一个商品信息-->
<association property="item" javaType="com.zhou.bean.Item">
<id column="i_id" property="i_id"/>
<result column="i_text" property="i_text"/>
<result column="i_price" property="i_price"/>
<result column="i_desc" property="i_dec"/>
</association>
</collection>
</collection>
</resultMap>
<!-- 根据外建关系查询所有用户之间的关系-->
<!-- 查询 用户 和 商品信息 多对多查询 由于 用户 和商品信息 没有直接关系 ,所以-->
<select id="userFindItemAll" resultMap="userItemFindAllResultMap" >
select id,name,sex,o_id,o_name,u_id,d_id,d_num
,d_price,orders_id,i_text,i_desc,i_price,i_id
from orders,USER,ordersdemo,item
WHERE orders.u_id=user.id AND ordersdemo.orders_id=orders.o_id
AND ordersdemo.item_id=item.i_id
</select>
</mapper>
测试
public String testUser(){
List list = userService.userFindItemAll();
for(int i=0 ;i< list.size();i++) {
System.out.print(list.get(i));
User u = (User) list.get(i);
List<Orders> l = u.getOrders();
for(int j=0 ;j<l.size();j++){
System.out.print(l.get(j));
Orders o = l.get(j);
List listOrdersDemo = o.getOrdersDemos();
for(int m=0;m<listOrdersDemo.size();m++){
System.out.print(listOrdersDemo.get(m));
OrdersDemo ordersdemo = (OrdersDemo)listOrdersDemo.get(m);
Item item = ordersdemo.getItem();
System.out.print(item);
}
}
System.out.println();
}
测试结果