# 你知道 Mybatis 框架如何实现级联关系吗?
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kbYHQfpy-1602664881939)(https://imgkr.cn-bj.ufileos.com/768074eb-5e03-4ad1-81ee-5432b6614e4a.jpg)]
## 级联关系实现的方式
- 一对一
- 一对多
## 案例实操
### 一对一关系
实现方式 resultType/resultMap
**接口方法**
~~~ java
/**
* 一对一关联查询 resultType
* @param userId
* @return
*/
UserDto queryUserCardInfoForResultType(@Param("userId")int userId);
~~~
**sql 查询**
~~~ xml
SELECT
u.id,
u.user_name AS userName,
u.user_pwd AS userPwd,
u.flag,
u.cid,
c.number
FROM
USER u
LEFT JOIN card c ON u.cid = c.id
WHERE
u.id = #{userId}
~~~
#### resultType **实现**
~~~ xml
SELECT
u.id,
u.user_name AS userName,
u.create_time,
u.flag,
u.cid AS cid,
c.number
FROM
User u
LEFT JOIN card c u ON u.cid =c.id
WHERE
u.id = #{id}
~~~
#### resultMap 实现
~~~ xml
SELECT u.id,u.user_name,u.true_name,l.role_name
FROM t_user u JOIN t_user_role r
ON (u.id = r.user_id) JOIN t_role l
on (r.role_id = l.id)
WHERE u.id = #{id}
~~~
#### resultMap + association实现
**resultMap** **映射定义**
~~~ xml
~~~
**查询**
~~~ xml
SELECT id, role_id FROM t_user_role WHERE id = #{id}
SELECT id, role_name , role_remark FROM t_role WHERE id = #{role_id}
~~~
### 一对多关系
实现方式:resultMap 实现
resultType 有局限,无法去重,需手动处理。
**ResultMap 定义 **
~~~ xml
~~~
查询
~~~ xml
select id, name , promotePrice FROM yg_goods WHERE id = #{id}
SELECT id , goods_skuid , goods_img FROM yg_goods_imgage where goods_skuid = #{id}
~~~
## 扩展
### sql
sql 元素用来定义一个**可以复用的 SQL 语句段**,供其它语句调用。比如:
~~~ xml
select
from user where userId = #{userId}
~~~
/sql>
select
from user where userId = #{userId}
~~~
###
需要视频配套文档或更多资料+我们程序员小姐姐v:lezijie007(加好友时备注:b站-LT,不备注拒绝添加哟)