云迈博客

您现在的位置是:首页 > 后端开发 > Java > 正文

Java

mybatisplus在resultMap一对多的情况下分页失败的解决方法

黄昊2022-09-14Java406
问题描述:查询分页时采用mybatis一对多的方式,使用resultMap配置去查询,结果出错原因:用错了mybatis一对多查询的方式改正:应该使用这种方式示例:创建表CREAT

问题描述:查询分页时采用mybatis一对多的方式,使用resultMap配置去查询,结果出错

原因:用错了mybatis一对多查询的方式

改正:应该使用这种方式

<collection property="list" ofType="com.cmf.pojo.TestChild" select="selectChild"  column="{testId=test_id}">

新建mapper方法

    Page<TestDto> selectList(Page<TestDto> page);

    List<TestChild> selectChild(String testId);

在mapper.xml中新建查询

  <resultMap id="resultMap" type="com.xxx.pojo.TestDto">
    <id property="testId" column="test_id" javaType="String" jdbcType="VARCHAR"/>
    <result property="testName" column="test_name" javaType="String" jdbcType="VARCHAR"/>
    <collection property="list" ofType="com.xxx.pojo.TestChild" >
      <id property="childId" column="child_id" javaType="String" jdbcType="VARCHAR"/>
      <result property="childName" column="child_name" javaType="String" jdbcType="VARCHAR"/>
      <result property="parentId" column="parent_id" javaType="String" jdbcType="VARCHAR"/>
    </collection>
  </resultMap>

  <select id="selectList" resultMap="resultMap">
    select t.*,tc.*
      from test1 t
      left join test_child  tc on tc.parent_id=t.test_id
    </if>
</select>

分页的查询其实是错误的,并没有查到test1表中的10条数据

mybatis还提供另一种分页查查询可以完美解决上面的问题

mapper.xml文件

  <resultMap id="resultMap" type="com.xxx.pojo.TestDto">
    <id property="testId" column="test_id" javaType="String" jdbcType="VARCHAR"/>
    <result property="testName" column="test_name" javaType="String" jdbcType="VARCHAR"/>
    <collection property="list" ofType="com.xxx.pojo.TestChild" select="selectChild"  column="{testId=test_id}">
    </collection>
  </resultMap>


  <select id="selectList" resultMap="resultMap">
    select t.*
      from test1 t
    </if>
  </select>

  <select id="selectChild" resultType="com.xxx.pojo.TestChild">
    select child_id childId,child_name childName,parent_id parentId from  test_child where parent_id=#{testId}
  </select>

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~