多表执行嵌套查询,减少笛卡尔积,防止内存溢出

 问题:当涉及四个表的查询时,会产生大量的笛卡尔积导致内存溢出。

解决办法 :可以使用嵌套查询将多表的联合查询拆分为单个表的查询,使用resultmap中的association(适合一对一) 或 collection(一对多) 来实现封装。

association(适合一对一) 或 collection(一对多)的理解可以参考这个 , 思想容易懂

http://t.csdnimg.cn/itH1Licon-default.png?t=N7T8http://t.csdnimg.cn/itH1L

collection参考这个 

http://t.csdnimg.cn/5XX7cicon-default.png?t=N7T8http://t.csdnimg.cn/5XX7c 

 <resultMap type="NodeVo" id="NodeVoResult">
        <result property="id"    column="id"    />
        <result property="nodeName"    column="node_name"    />
        <result property="address"    column="address"    />
        <result property="businessType"    column="business_type"    />
        <result property="regionId"    column="region_id"    />
        <result property="partnerId"    column="partner_id"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
        <result property="createBy"    column="create_by"    />
        <result property="updateBy"    column="update_by"    />
        <result property="remark"    column="remark"    />
        <result property="vmCount"    column="vm_count"    />
<!--    property 对应实体类的字段  javatype对应这个字段的类型 column对应查询对应的条件 select 对应查询的方法,全路径    -->
<!--        为了防止多表联查产生大量笛卡尔积导致内存溢出,使用嵌套查询-->
        <association property="region" javaType="Region" column="region_id" select="com.dkd.manage.mapper.RegionMapper.selectRegionById"/>
        <association property="partner" javaType="Partner" column="partner_id" select="com.dkd.manage.mapper.PartnerMapper.selectPartnerById"/>
    </resultMap>
    <select id="selectNodeVoList" resultMap="NodeVoResult">
        SELECT
        n.id,
        n.node_name,
        n.address,
        n.business_type,
        n.region_id,
        n.partner_id,
        n.create_time,
        n.update_time,
        n.create_by,
        n.update_by,
        n.remark,
        COUNT(v.id) AS vm_count
        FROM
        tb_node n
        LEFT JOIN
        tb_vending_machine v ON n.id = v.node_id
        <where>
--              字段名不唯一的时候一定指定是哪个表的字段
            <if test="nodeName != null  and nodeName != ''"> and n.node_name like concat('%', #{nodeName}, '%')</if>
            <if test="regionId != null "> and n.region_id = #{regionId}</if>
            <if test="partnerId != null "> and n.partner_id = #{partnerId}</if>
        </where>
        GROUP BY
        n.id
    </select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值