1. 程式人生 > 其它 >帶有collection的分頁查詢導致每頁條數錯誤的解決方法

帶有collection的分頁查詢導致每頁條數錯誤的解決方法

技術標籤:mybatismysql

  • 問題

    由於巢狀結果方式會導致結果集被摺疊,因此分頁查詢的結果在摺疊後總數會減少

    <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查詢,他會自己查詢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>