作用:解决表与表的关联(个人理解)
表关系:一个boy对多个Beauty
public class Beauty {
private int id;
private String name;
private LocalDateTime bornDate;
private String phone;
private Boy boyFriend;
}
public class Boy {
private int id;
private String name;
private List<Beauty> beauties;
}
result 解释 属性名与列名的对应关系
associate 一对一/一对多
associate 也可以看做是result的一种,只不过它所代表属性是一个类,又嵌套reslut来解释这个类的对应关系
- 模板
<select id="绑定接口方法名" resultMap="自定义resultMap名">
sql语句
</select>
<resultMap id="自定义resultMap名" type="返回类型">
<!-- result 建立类型中属性(property)和表中列名(column)的关系-->
<result property="类型中属性" column="列名"/>...
<!--association这里的属性是一个类 -->
<association property="属性名" javaType="类型">
<result property="id" column="bid"/>...
</association>
</resultMap>
- 实例
<select id="getBoyFriendById" resultMap="Beauty">
select bt.id,bt.name,bt.borndate,b.id bid ,b.boyName
from beauty bt,boys b
where b.id = bt.boyfriend_id and bt.id = #{id}
</select>
<resultMap id="Beauty" type="pojo.Beauty">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="bornDate" column="borndate"/>
<result property="phone" column="phone"/>
<association property="boyFriend" javaType="pojo.Boy">
<result property="id" column="bid"/>
<result property="name" column="boyName"/>
</association>
</resultMap>
collection 一对多
- 模板
<select id="绑定接口方法名" resultMap="自定义resultMap名">
sql语句
</select>
<resultMap id="自定义resultMap名" type="返回类型">
<result property="类型中属性" column="列名"/>...
<!--collection这里的属性是一个带泛型的集合,泛型约束为要解释对应关系的类型 -->
<collection property="beauties" ofType="Beauty">
<result property="id" column="id"/>...
</collection>
</resultMap>
- 实例
<select id="getAllGirlsById" resultMap="Boy">
select g.id,g.name,g.borndate,b.id bid ,b.boyName
from beauty g, boys b
where g.boyfriend_id = b.id and b.id = #{id}
</select>
<resultMap id="Boy" type="Boy">
<result property="id" column="bid"/>
<result property="name" column="boyName"/>
<collection property="beauties" ofType="Beauty">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="bornDate" column="borndate"/>
<result property="phone" column="phone"/>
</collection>
</resultMap>