Mybatis 多对多关联查询的两种方式:嵌套结果与嵌套查询

本文详细解析了MyBatis中多对多关系的映射方法,包括使用中间表建立连接关系,以及通过嵌套结果和嵌套查询实现一对多和多对多的数据映射。介绍了Mapper接口和MapperXML配置的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先决条件

  1. 多对多需要一种中间表建立连接关系
  2. 多对多关系是由两个一对多关系组成的,一对多可以也可以用两种方式实现

嵌套结果

Mapper 接口

List<TUser> selectUserRole();

Mapper XML配置

<select id="selectUserRole" resultMap="userRoleInfo">
	select a.id, 
	   a.userName,
	   a.realName,
	   a.sex,
	   a.mobile,
	   a.note,
	   b.role_id,
	   c.role_name,
	   c.note role_note
	from t_user a,
	   t_user_role b,
	   t_role c
	where a.id = b.user_id AND 
	   b.role_id = c.id
</select>	

t_user_role 就是中间表,只有两列,user_id、role_id

嵌套查询

Mapper 接口

List<TRole> selectRoleandUsers();

Mapper XML配置

<resultMap id="RoleandUsers" type="TRole" extends="BaseResultMap">
	<collection property="users" fetchType="lazy"  column="id" select="com.enjoylearning.mybatis.mapper.TUserMapper.selectUserByRoleId"></collection>
</resultMap>
<select id="selectRoleandUsers" resultMap="RoleandUsers">
	select 
		<include refid="Base_Column_List" />
	from t_role
</select> 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值