您的位置:首页 > 其它

MyBatis笔记:一对多关联查询之多表连接查询

2018-03-17 14:31 405 查看
此仅为个人笔记,若有不周之处,万望指正,不胜感激。





为此我建立了两个表,一个为Country,内含cid,cname两个列,cid为主键;包含一个为Minister,内含mid,mname,countryId三个列,mid为主键。Country与Minister呈一对多关联,一个Countru关联多个Minister,Minister中哪一行countryId的值与Country中哪一行cid的值相同,这两行便相关联。public class Country {
private Integer cid;
private String cname;
private Set<Minister> ministers;
//为节省篇幅,自行补全get,set及toString方法
}
public class Minister {
private Integer mid;
private String mname;
//为节省篇幅,自行补全get,set及toString方法
}
此为Country,Minister两个POJO。<mapper namespace="com.bjpowernode.dao.ICountryDao">

<resultMap type="com.bjpowernode.beans.Country" id="countryMapper">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
<collection property="ministers" ofType="com.bjpowernode.beans.Minister">
<id column="mid" property="mid"/>
<result column="mname" property="mname"/>
</collection>
</resultMap>

<select id="selectCountryById" resultMap="countryMapper">
select cid,cname,mid,mname
from country,minister
where countryId=cid and cid=#{cid}
</select>

</mapper><collection/>标签用于映射集合,在上述映射文件中使用<collection/>标签体现出两个实体对象间的关联关系:
    property:指定关联属性,即Country类中的集合属性
    ofType:集合属性的泛型类型

先行以com.bjpowernode.beans.Country封装了一个countryMapper的resultMap,若在表Country的列cid中找到与#{cid}中cid值相同的行,而后又到表Minister中以#{cid}查询与表Country关联的行,随后将结果以countryMapper返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: