今天在使用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>