2019-03-22 多对多查询

需求

查询用户及用户购买的商品信息

sql语句

查询主表是:用户表
关联表:由于用户和商品没有直接关联,通过订单和订单明细进行关联,所有关联表:
orders、orderdetail、items

SELECT 
        orders.*,
        user.username,
        user.sex,
        user.address,
        orderdetail.id orderdetail_id,
        orderdetail.items_id,
        orderdetail.items_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

映射思路

将用户信息映射到User中。
在User类中添加订单列表属性 List<Orders> orderslist,将用户创建的订单映射到orderslist
在Orders类中添加订单明细列表属性 List<OrderDetail> orderdetail,将订单的明细映射到orderdetail
在OrderDetail类中添加Items属性,将订单明细所对应的商品映射到Items

mapper.xml

<!-- 查询用户及商品信息 -->
    <resultMap type="cn.iven.mybatis.po.User" id="UserAndItemsResultMap">
        <!-- 用户信息 -->
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
    
        <!-- 订单信息 
        一个用户对应多个订单,使用collection映射-->
        <collection property="ordersList" ofType="cn.iven.mybatis.po.Orders">
            <id column="id" property="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.iven.mybatis.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"/>
                
                <!-- 商品信息
                一个订单明细对应一个商品 -->
                <association property="items" javaType="cn.iven.mybatis.po.Items">
                    <id column="items_id" property="id"/>
                    <result column="items_name" property="name"/>
                    <result column="items_price" property="price"/>
                    <result column="items_detail" property="detail"/>
                </association>
            </collection>
        </collection>
    </resultMap>

mapper.java

测试

多对多查询总结

将查询用户购买的商品信息明细清单,(用户名,用户地址,购买商品名称,购买商品时间,购买商品数量)
针对上边的需求就使用resultType将查询到的记录映射到一个扩展的pojo中,很简单实现明细清单的功能。

一对多是多对多的特例,如下需求:
查询用户购买的商品信息,用户和商品的关系是多对多关系。
需求1:
查询字段:用户账号、用户名称、用户性别、商品名称、商品价格(最常见)
企业开发中常见明细列表,用户购买商品明细列表,
使用resultType将上边查询列映射到pojo输出。

需求2:
查询字段:用户账号、用户名称、购买商品数量、商品明细(鼠标移上显示明细)
使用resultMap将用户购买的商品明细列表映射到User对象中。

总结:

使用resultMap是针对那些对查询结果映射有特殊要求的功能,比如特殊要求映射成list中包括多个list。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容