今天在使用MyBatis查詢數據時,發現查出來的數據和List集合的大小不一致,如下圖所示,Total爲3,但是list集合size爲2.
List<ArticleCommentToShow> commentsByArticleId = articleCommentService.getCommentsByArticleId(article.getArticleId());
logger.info("長度:" + commentsByArticleId.size());
/**
* 評論用戶頭像
*/
private String imagePath;
/**
* 評論用戶的用戶名
*/
private String userName;
/**
* 評論實體類
*/
private ArticleComment articleComment;
ArticleCommentShow中包含了一個實體類ArticleComment,在查詢的時候我使用了resultMap查詢,對應的查詢如下圖所示
<!--對應於getCommentsByArticleId的需要字段-->
<sql id="wholeCommon">
user_name,image_path,article_comment_id,comment_content, comment_time, to_id,article_comment.user_id,article_comment.article_id,to_user_id
</sql>
<!--根據文章ID獲取評論-->
<select id="getCommentsByArticleId" resultMap="CommentsResult">
select
<include refid="wholeCommon"/>
from article_comment,user
<where>
(article_id = #{articleId} and article_comment.user_id = user.user_id)
</where>
</select>
<resultMap id="CommentsResult" type="com.molihub.entity.ArticleCommentToShow">
<result property="userName" column="user_name"/>
<result property="imagePath" column="image_path"/>
<association property="articleComment" javaType="com.molihub.entity.ArticleComment">
<id property="articleCommentId" column="article_comment_id"/>
<result property="articleId" column="article_id"/>
<result property="commentContent" column="comment_content"/>
<result property="commentTime" column="comment_time"/>
<result property="toId" column="to_id"/>
<result property="userId" column="user_id"/>
<result property="toUserId" column="to_user_id"/>
</association>
</resultMap>
經過不斷的百度,查資料,發現是因爲我的查出來的數據沒有主鍵,因爲我查出來的數據格式類似這樣:list: [1,a],[2,a],[3,b],這裏的字母爲實體類,所以當實體類重複的時候,MyBatis會自動去重,用最新的數據替換之前“重複”的數據。
解決辦法是:1.添加主鍵,用於區分重複數據,2.禁用二級緩存,否則雖然第一次查出來的數據是正常的,但是再次查詢的時候會發現數據依然缺少。
經過修改,resultMap改爲如下格式
<resultMap id="CommentsResult" type="com.molihub.entity.ArticleCommentToShow">
<id property="articleComment.articleCommentId" column="article_comment_id"/>
<result property="userName" column="user_name"/>
<result property="imagePath" column="image_path"/>
<result property="articleComment.articleId" column="article_id"/>
<result property="articleComment.commentContent" column="comment_content"/>
<result property="articleComment.commentTime" column="comment_time"/>
<result property="articleComment.toId" column="to_id"/>
<result property="articleComment.userId" column="user_id"/>
<result property="articleComment.toUserId" column="to_user_id"/>
</resultMap>