mybatis一对多分页条数错误问题

问题描述

因为最近在搭建我的个人博客。在博客中会存在一些一对多的数据。比如前端加载文章。每个文章包含了两到三个标签不固定。分页插件使用的是pageHelper。当时没想那么多。心里想着不就直接可以使用join进行关联查询完了在Map中使用< collection >标签做下一对多映射就行了吗。运行代码。没有报错。一开始数据比较少也没有发现问题。随着数据越来越多我突然发现了问题。就是每页分页展示的数据条数不对。

原因分析

发现了问题。在代码中寻找。发现如果使用上述的方法来处理。因为存在着一对多的关系。所以查询的结果文章好多是重复的。这个时候对其进行分页。虽然查询到的结果是分页的条数。但是在mybatis对其进行一对多映射的时候就变成了不固定的数量,
以前的mapper

 <select id="queryArticleByExample" resultMap="ArticleMap">
    select a.id,a.id as article_id,a.name,a.introduction,
    a.is_original,a.is_top,a.thum,a.author,a.create_time,
    a.update_time,a.is_show,a.content
    from article a
    left join article_label al on a.id = al.article_id 
    left join label l on al.label_id = l.id
 </select>

查询出来的结果为
在这里插入图片描述
这个时候对其分页。 最终的数量一定是不正确的。

解决办法

通过查询资料发现可以通过在mapper中父子查询的方法来解决这个问题。
mapper代码

<resultMap id="ArticleMap" type="top.demo.vo.article.ArticleVo">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="introduction" jdbcType="VARCHAR" property="introduction" />
    <result column="is_original" jdbcType="BIT" property="isOriginal" />
    <result column="is_top" jdbcType="BIT" property="isTop" />
    <result column="thum" jdbcType="VARCHAR" property="thum" />
    <result column="author" jdbcType="VARCHAR" property="author" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
    <result column="is_show" jdbcType="BIT" property="isShow" />
    <result column="content"  property="content"/>
    <!-- column 为父子查询的公共字段。 select后为子查询的id -->
    <collection property="labels" ofType="top.demo.dao.model.Label" column="article_id" select="queryLabelByarticleId">
      <id column="labelId" jdbcType="INTEGER" property="id" />
      <result column="labelName" jdbcType="VARCHAR" property="name" />
    </collection>
  </resultMap>

父查询

 <select id="queryArticleByExample" resultMap="ArticleMap">
    select a.id,a.id as article_id,a.name,a.introduction,
    a.is_original,a.is_top,a.thum,a.author,a.create_time,
    a.update_time,a.is_show,a.content
    from article a
 </select>

子查询

  <select id="queryLabelByarticleId" resultType="top.demo.dao.model.Label">
        select * from article_label al
        left join label l on al.label_id = l.id and l.is_show = 1
        where al.article_id = #{article_id}
  </select>

这样最终返回的条数是分页的数量。而且可以查询到一对多的标签。

最后欢迎大家来我的个人博客看看。嘻嘻
zShare个人博客

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

残城碎梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值