Mybatis處理一對多關系下的查詢方法
封裝結果集resultMap
假設一則新聞信息對應多個新聞圖片
在新聞信息實體類下
public class Info_Img {
private Integer infoId;
private String content;
private List<Img> imgs;
}
圖片實體類
public class Img {
private Integer imgId;
private String url;
private Integer infoId;//外鍵
}
映射SQLMapper xml文件的結果集resultMap寫法
<resultMap id="BaseResultMap" type="com.example.project.entity.Info_Img">#type填寫項目路徑相應的實體類
<id column="info_id" jdbcType="INTEGER" property="infoId" />
<collection property="imgs" ofType="com.example.project.entity.Img" javaType="java.util.ArrayList">
<id column="img_id" jdbcType="INTEGER" property="imgId" />
<result column="url" jdbcType="VARCHAR" property="url" />
<result column="info_id" jdbcType="INTEGER" property="InfoId" />
</collection>
</resultMap>
<select id="findAll" resultMap="BaseResultMap">
select
b.info_id,
i.img_id,i.url
FROM
info AS b,
img AS i
</select>
注意 :查詢結果一定要含有主鍵id,以至於collection對結果進行合並處理成數組類型,且字段必須對應