在上手mybatis一對多時就遇到了個巨坑:
Mapped Statements collection does not contain value
在網上查了大量資料都無法解決,或者說是我不夠理解那些解決方案。
<select id="selectComment" resultMap="shareCommentResult">
select c.*,
l.id is not null is_like,
#{param2} as u_account
from cat_share_comment c
left join cat_share_like l on c.id = l.host_id and l.part_code = 2 and l.account = #{param2}
where c.host_id = #{param1}
</select>
<resultMap id="shareCommentResult" type="xyz.ganbug.gdutdemo.model.cat.CatShareCommentVo">
<id column="id" property="id"/>
<result column="account" property="account"/>
<result column="wx_name" property="wxName"/>
<result column="host_id" property="hostId"/>
<result column="avatar_url" property="avatarUrl"/>
<result column="text" property="text"/>
<result column="like_num" property="likeNum"/>
<result column="comment_num" property="commentNum"/>
<result column="is_like" property="isLike"/>
<result column="create_date" property="createDate"/>
<result column="create_time" property="createTime"/>
<result column="timestamp" property="timestamp"/>
<collection property="comments" ofType="xyz.ganbug.gdutdemo.model.cat.CatShareComment2Vo"
select="xyz.ganbug.gdutdemo.mapper.CatShareMapper.selectComment2sForComment"
column="{id=id,account=u_account}"/>
</resultMap>
<select id="selectComment2sForComment" resultMap="shareComment2">
select c.*,
l.id is not null is_like
from cat_share_comment2 c
left join cat_share_like l on c.id = l.host_id and l.part_code = 2 and l.account = '3117002575'
where c.host_id = #{id}
</select>
分析:selectComment
中select c.*,
要注意,我天真的以爲它等同於沒有前綴c.,如c.id 跟 id一樣,事實是在一般的映射中確實如此,都是如果要映射到屬性column中那就大錯特錯了。
所以應該這樣修改:
把
<collection property="comments" ofType="xyz.ganbug.gdutdemo.model.cat.CatShareComment2Vo"
select="xyz.ganbug.gdutdemo.mapper.CatShareMapper.selectComment2sForComment"
column="{id=id,account=u_account}"/>
修改成(不要忽略前綴c.)
<collection property="comments" ofType="xyz.ganbug.gdutdemo.model.cat.CatShareComment2Vo"
select="xyz.ganbug.gdutdemo.mapper.CatShareMapper.selectComment2sForComment"
column="{id=c.id,account=u_account}"/>