带有collection的分页查询导致每页条数错误的解决方法

  • 问题

    由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少

    <resultMap id="baseResultMap" type="com.jia.Student">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <collection property="bookList" ofType="com.jia.Book">
            <result column="book_id" property="id"/>
            <result column="student_id" property="studentId"/>
            <result column="amount" property="amount"/>
        </collection>
    </resultMap>
    
    <select id="getStudent" resultMap="baseResultMap">
        SELECT
            Student.id,
            Student.`name`,
            Student.gender,
            book.id book_id,
            book.student_id,
            book.amount
        FROM
            student
            left join book on book.student_id=student.id
        WHERE
            student.is_delete=0
        limit 
        	#{pageNumber} ,#{pageSize}
    </select>
    
  • 解决方法

    使用collection里的select定义查询,条件是上层student的id

    执行过程是,先执行getStudent的查询,将学生全都查询出来并进行分页,这种情况下分页是没问题的,然后再去查询每个学生对应的多条书本信息,走collection里的select查询,使用的条件是第一次查询结果中的主键id,然后他会自己查询book信息封装到每个对应的student中,完成查询。

    <resultMap id="baseResultMap" type="com.jia.Student">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <collection property="bookList" ofType="com.jia.Book" select="selectBook" column="id">
            <result column="book_id" property="id"/>
            <result column="student_id" property="studentId"/>
            <result column="amount" property="amount"/>
        </collection>
    </resultMap>
    
    <select id="getStudent" resultMap="baseResultMap">
        SELECT
            Student.id,
            Student.`name`,
            Student.gender
        FROM
            student
        WHERE
            student.is_delete=0
        limit 
        	#{pageNumber} ,#{pageSize}
    </select>
    
    <select id="selectBook" resultType="com.jia.Book">
        select * from  book where book.student_id=#{id}
    </select>
    
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值