返回

Mybatis源码分析(十三) - 关联查询之多对多

发布时间:2022-12-06 18:21:37 296

 

我的理解是,多对多其实就是两个一对多。

嵌套结果:

示例代码:

 
<select id="selectUserRole" resultMap="userRoleInfo">
select a.id,
a.user_name,
a.real_name,
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>

<resultMap type="TUser" id="userRoleInfo" extends="BaseResultMap">
<collection property="roles" ofType="TRole" columnPrefix="role_">
<result column="id" property="id" />
<result column="Name" property="roleName" />
<result column="note" property="note" />
</collection>
</resultMap>

嵌套查询:

<select id="selectUserbyrole" resultMap="userRoleInfo1">
select * from t_role a
</select>

<resultMap id="userRoleInfo1" extends="BaseResultMap" type="TRole">
<collection property="users" column="id"
select= "com.enjoylearning.mybatis.mapper.TUserMapper.selectUsers12" fetchType="lazy"></collection>
</resultMap>
 
<select id="selectUsers12" resultMap="BaseResultMap">
SELECT a.id, a.user_name,
a.real_name,
a.sex,
a.mobile,
a.note
FROM t_user a,t_user_role b
WHERE a.id = b.user_id AND b.role_id=#{id}
</select>
@Test
// 多对多
public void testManyToMany1() {
// 2.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取对应mapper
TRoleMapper mapper = sqlSession.getMapper(TRoleMapper.class);
// 4.执行查询语句并返回结果
// ----------------------
List list = mapper.selectUserbyrole();
for (TRole tUser : list) {
System.out.println(tUser.getUsers().size());
}
}

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
Mybatis源码分析(十五) - 缓存技术 2022-12-06 17:36:32