MyBatis一對多嵌套list返回結果集以及分頁查詢問題處理


這兩天在整理原有系統接口時,遇到后端的人員-角色-菜單的權限接口沒有進行連表的關聯查詢操作,前端拿數據非常不方便,現在將接口相關sql進行修改並讓前端可以一次性拿到想要的數據

原有的單表簡單sql:

     <select id="queryList" resultType="com.framework.entity.SysRoleEntity"> select * from sys_role order by role_id asc <if test="offset != null and limit != null"> limit #{offset}, #{limit} </if>
    </select>

修改為嵌套list返回結果集的查詢(關鍵點:使用resultMap中的collection標簽):

注意將select中的resultType修改為resultMap

    <resultMap id="BaseResultMap" type="com.framework.entity.SysRoleEntity">
        <id column="role_id" property="roleId" jdbcType="INTEGER"></id>
        <result column="role_name" property="roleName" jdbcType="VARCHAR"></result>
        <result column="remark" property="remark" jdbcType="VARCHAR"></result>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"></result>
        <collection property="menuIdList" resultMap="menuIdListMap" />
    </resultMap>
    <resultMap id="menuIdListMap" type="java.lang.Long">
        <id column="menu_id" property="id" javaType="Long"></id>
    </resultMap>
     <select id="queryList" resultMap="BaseResultMap"> select r.role_id, r.role_name, r.remark, r.create_time, rm.menu_id from sys_role r left join sys_role_menu rm on r.role_id=rm.role_id order by r.role_id asc <if test="offset != null and limit != null"> limit #{offset}, #{limit} </if>
    </select>

現在這樣子是已經達到返回結果集中嵌套list的效果

但是同時也帶來另外一個問題:分頁參數對應的是left join后的限制,並不是我們預期只對主表的分頁限制,所以sql語句還需要進一步完善:

使用where條件,將分頁參數當做一個查詢子集,然后再利用 關鍵字IN 實現(由於IN關鍵字不可與limit在同一個語句使用,所以需要創建一個臨時表)

sql最終結果:

     <select id="queryList" resultMap="BaseResultMap"> select r.role_id, r.role_name, r.remark, r.create_time, rm.menu_id from sys_role r left join sys_role_menu rm on r.role_id=rm.role_id <where>
             <if test="offset != null and limit != null"> r.role_id IN (SELECT temp.role_id from (SELECT role_id FROM sys_role limit #{offset}, #{limit}) AS temp) </if>
         </where> order by r.role_id asc <!--<if test="offset != null and limit != null"> limit #{offset}, #{limit} </if>-->
    </select>

 最終完成修改,發布測試,這里mark一下修改大致過程,希望能夠幫助有需要的同學


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM