带有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>

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

推荐阅读更多精彩内容