MyBatis一对多导致PageHelper分页返回total数据不正确

975 阅读1分钟

MyBatis一对多,导致PageHelper分页返回total数据不正确

pagehelper版本

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

A表是一,B表是多

正确写法

resultMap 中使用 select 进行嵌套查询

  1. 原先关联查询 sql 拆分成两个,不进行关联查询
<select id="selectA" resultType="com.A">
    SELECT a.id, a.create_time
    FROM a_table AS a
</select>

<select id="selectB" resultType="java.lang.String">
    SELECT b.name
    FROM b_table AS b
    WHERE b.a_id = #{id}
</select>
  1. collectionselect 指向 selectB 查询语句,column 指向 selectA 中查询出来的 a.id
<resultMap id="bMap" type="com.A">
    <id column="id" property="id"/>
    <result column="create_time" property="createTime"/>
    <collection property="productId" select="selectB" column="id">
        <result column="name"/>
    </collection>
</resultMap>