02-Mybatis-06-关联关系查询

一对多

以一个Country包好多个Minister为例

多表连接查询

	private Integer cid;
	private String cname;
	// 关联属性
	private Set<Minister> ministers;
<resultMap type="Country" id="countryMapper">
	<id column="cid" property="cid"/>
	<result column="cname" property="cname"/>
	<collection property="ministers" ofType="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 = #{xxx}
</select>
  • 说明:

    • sql语句中的cidcname,可以通过反射机制获取到Country类中的cidcname属性值!
    • 而对于Minister中的属性:midmname来说,由于在Country类中找不到,此时用到了select标签中的resultMap属性;
    • resultMap标签,其对Country进行了补充说明(当然是对电脑来说),告诉它,有cidcname两列;并且还有一个集合叫做ministers,类型是Minister:它包括midmname两列!
  • 特别说明:属性是指,get或set方法的方法名,去掉get或set以后剩余部分首字母小写,那么这个东西就是属性!

多表单独查询

  • 而以上方式用的较少,以下是以后用的比较多的方式
<select id="selectMinisterByCountry" resultType="Minister">
	select mid,mname from minister where countryId = #{ooo}
</select>

<resultMap type="Country" id="countryMapper">
	<id column="cid" property="cid"/>
	<result column="cname" property="cname"/>
	<collection property="ministers" 
				ofType="Minister"
				select="selectMinisterByCountry"
				column="cid"/>
</resultMap>

<select id="selectCountryById" resultMap="countryMapper">
	select cid,cname from country where cid = #{xxx}
</select>
  • 说明:
    • 以上代码表示的是多表单独查询;
    • 以后用的比较多,因为这种方式可以使用延迟加载;
    • 上面的多表查询不能使用延迟加载。

多对一

多表连接查询

同理

多表单独查询

同理

自关联

本质上同理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值