N-1 映射
N-1映射 即 多结果集(第一个返回的结果集不算)返回的结果集中又是个多结果集
所谓的多结果集就是执行一条语句,数据库返回多个结果集,这种请款一般在调用存储过程的时候出现。
有两个表,和两个存储过程。
表 address
表 person
注:address表的 address_personId列 参照 person表 person_id列,两者一一对应
delimiter //
create procedure p_get_person_address(in id int)
begin
select * from person where person_id >= id;
select * from address where address_personId >= id;
end;
create procedure p_get_address_person(in content varchar(225))
begin
select * from address where address_content regexp content;
select * from person where person_id in
(select address_personId from address where address_content regexp content);
end;
delimiter ;
思路:调用某个存储过程,会返回两个结果集,对于MyBatis而言这两个结果集没有任何关系,所以我们要做的就是要把他们的联系指明,即两者列与列之间的参照关系(指定column列和foreignColumn列)。
还有,一般我们只返回一个结果集,那么我们对某个select语句配置ResultMap的时候,就是配置这唯一的结果集与java对象属性之间的映射关系,但是,现在有多个结果集了,所以select语句应该为多个结果集指名字(resultSets属性,按照结果集返回顺序一一对应,不同结果集之间用,隔开,千万不能加多余的空格!!!),然后拿着这个名字去配置映射关系。
<select id="queryPerson" resultMap="personMap" statementType="CALLABLE" resultSets="pe,ad">
{call p_get_person_address(#{a})}
</select>
<resultMap id="personMap" type="person">
<id column="person_id" property="id"/>
<result column="person_name" property="name"/>
<result column="person_age" property="age"/>
<association resultSet="ad" property="address"
column="person_id" foreignColumn="address_personId"
resultMap="com.lyx.dao.AddressMapper.addressMap"/>
</resultMap>
<select id="queryAddress" resultMap="addressMap" statementType="CALLABLE" resultSets="ad,pe">
{call p_get_address_person(#{a})}
</select>
<resultMap id="addressMap" type="address">
<id column="address_id" property="id"/>
<result column="address_content" property="content"/>
<result column="address_personId" property="personId"/>
<association resultSet="pe" property="person"
column="address_personId" foreignColumn="person_id"
resultMap="com.lyx.dao.PersonMapper.personMap"/>
</resultMap>
注意点:
1、select标签与association标签中的resultSets一一对应。
2、程序总是默认配置第一个返回的结果集,所以第一个例子的resultMap 并没有指定resultSets=“pe”属性,同样第二例子的resultMap也没有指定resultSets=“ad”属性。
3、两个表对MyBatis而言并无关联,所以我们要指定两表之间的参照关系。
column为默认结果集(resultMap 中直接配置的结果集)的某个列
foreignColumn 为association 指定的 ResultSets中的某个列。
当这两个列的值相等时,则关联两表。
N-N 映射
N-N映射 即 多结果集(第一个返回的结果集不算)返回的结果集|中只有一条记录
和N-1映射基本是一样的,有变更的地方为
1、两者的sql语句肯定是不同的
2、这个时候,这个特殊属性(上面提到的)的类型一般为集合类型
3、associate标签 换成 collection 标签
4、在 collection 新增两个 属性
**javaType:**就是指特殊属性的java类型,一般为集合类型
**ofType:**指结合类型里面所装的数据类型(一般就是集合泛型)
其实很多时候可以不用指定javaType属性,因为MyBatis能推断出来他的类型,并且如果集合准确使用了泛型,那么ofType都可以不用了。
其他与N-1映射一模一样