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