使用 MyBatis resultMap 進行一對多關聯查詢(如商品與圖片),預期返回多條商品記錄,實際卻只拿到最後一條數據。SQL 在資料庫直接執行卻能正常返回多行。
id 屬性缺失或重複resultMap 中的 <id> 標籤用於標識唯一性。若映射的主鍵列(如 tb_item.id)未在 <id> 中聲明,或多條記錄的主鍵值相同,MyBatis 會將其視為同一對象而覆蓋合併,導致結果列表只剩最後一條。
SELECT tb_item.id AS item_id, ...。<resultMap> 中添加 <id property="id" column="item_id"/>。<collection> 的 ofType 指向正確的子對象類,column 對應外鍵。<resultMap id="itemPicMap" type="Item">
<id property="id" column="item_id"/>
<result property="name" column="item_name"/>
<collection property="pics" ofType="ItemPic">
<id property="id" column="pic_id"/>
<result property="url" column="pic_url"/>
</collection>
</resultMap>
<select id="selectItemAndPic" resultMap="itemPicMap">
SELECT
tb_item.id AS item_id,
tb_item.name AS item_name,
tb_item_pic.id AS pic_id,
tb_item_pic.url AS pic_url
FROM tb_item
LEFT JOIN tb_item_pic ON tb_item.id = tb_item_pic.item_id
WHERE tb_item.id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
resultMap 是否有 <id> 且列名與 SQL 別名一致?equals/hashCode 是否基於主鍵實現?resultType 而非 resultMap?補全主鍵映射後,MyBatis 能正確識別每條主記錄,一對多結果即可完整返回。