首页 > 编程语言 >Mybatis源码分析(十三) - 关联查询之多对多

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

时间:2022-11-30 14:41:51浏览次数:38  
标签:mapper name 查询 note 源码 role user Mybatis id


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

嵌套结果:

示例代码:

<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<TRole> list = mapper.selectUserbyrole();
for (TRole tUser : list) {
System.out.println(tUser.getUsers().size());
}
}

 

标签:mapper,name,查询,note,源码,role,user,Mybatis,id
From: https://blog.51cto.com/u_14906615/5899409

相关文章