pageHelper使用过程中遇到的一些问题:当查询的结果包含list时查询出来的结果不对
例如:一篇文章-----一个分类------多个标签;这里的标签要用list,对应sql语句中的collection,PageInfo.getTotal()得到的结果就会以查询出来的标签的总数来算,并不是按照文章个数来算
以下这种方式不适用pageHelper分页查询
<select id="queryArticleInfo" resultMap="queryArticleInfoMap">
select ta.id taID,title,author,des,tc.id tcID,tc.name tcName,tt.id ttID,tt.name ttName,modified_time,traffic,article_picture
from tb_article ta, tb_tag tt, tb_category tc, tb_article_category tac , tb_article_tag tat
where ta.id=tac.article_id and tac.category_id=tc.id and ta.id=tat.article_id and tat.tag_id = tt.id
</select>
<resultMap id="queryArticleInfoMap" type="ArticleInfoVO">
<result property="id" column="taID"/>
<result property="title" column="title"/>
<result property="author" column="author"/>
<result property="des" column="des"/>
<result property="traffic" column="traffic"/>
<result property="modifiedTime" column="modified_time"/>
<result property="articlePicture" column="article_picture"/>
<association property="category" ofType="Category">
<result property="id" column="tcID"/>
<result property="name" column="tcName"/>
</association>
<!-- tagList分页查询时(分页大小为一测试)该list会被拆分成单独的一个 查询的结果会比实际结果多-->
<collection property="tagList" ofType="Tag">
<result property="id" column="ttID"/>
<result property="name" column="ttName"/>
</collection>
</resultMap>
当一个文章包含多个标签时,查询的结果记录数是按照总的标签数来计算的---------结果会比实际结果多
原因:实际上是结果集映射 pageHelper使用分页时,会对select语句进行
select count(0)
from tb_article ta, tb_tag tt, tb_category tc, tb_article_category tac ,tb_article_tag tat
where ta.id=tac.article_id and tac.category_id=tc.id and ta.id=tat.article_id and tat.tag_id = tt.id
可以看到该结果并不是对最终的结果集(标签包含在文章里面算作一条记录)计算的,所以总条数会比想要得到的结果多!
暂时解决方案:采用子查询(但是查询次数增多)
<select id="queryArticleInfo" resultMap="queryArticleInfoMap">
select id ,title,author,des,modified_time,traffic,article_picture
from tb_article
</select>
<!--这样先查询文章,再去子查询分类及标签,总条数以文章的个数为准就不会被list影响,最终结果就是想要的-->
<resultMap id="queryArticleInfoMap" type="ArticleInfoVO">
<result property="id" column="id"/>
<result property="modifiedTime" column="modified_time"/>
<result property="articlePicture" column="article_picture"/>
<association property="category" column="id" javaType="Category" select="getCategoryInfo"/>
<collection property="tagList" column="id" javaType="ArrayList" ofType="Tag" select="getTagInfo"/>
</resultMap>
<!--对象子查询,这个不是主要原因-->
<select id="getCategoryInfo" resultType="Category">
select tc.id ,tc.name
from tb_category tc , tb_article_category tac
where tac.category_id=tc.id and tac.article_id=#{id}
</select>
<!--集合子查询,一个文章有多个标签 这个是导致上一种方法结果不正确的主要原因 -->
<select id="getTagInfo" resultType="Tag">
select tt.id ,tt.name
from tb_tag tt , tb_article_tag tat
where tat.tag_id=tt.id and tat.article_id=#{id}
</select>
版权声明:本文为m0_47428652原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。