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.contentfrom article aleft join article_label al on a.id = al.article_id left join label l on al.label_id = l.idselect>
查询出来的结果为

这个时候对其分页。 最终的数量一定是不正确的。
解决办法
通过查询资料发现可以通过在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"/><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.contentfrom article aselect>
子查询
<select id="queryLabelByarticleId" resultType="top.demo.dao.model.Label">select * from article_label alleft join label l on al.label_id = l.id and l.is_show = 1where al.article_id = #{article_id}select>
这样最终返回的条数是分页的数量。而且可以查询到一对多的标签。
最后欢迎大家来我的个人博客看看。嘻嘻
zShare个人博客
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
