mybatis plus 多表查询_SSM框架(七):mybatis多表查询--2,多对多查询

3、多对多

建立两张表:用户表,角色表

让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含各自的主键,在中间表中是外键。

2875b805cbdd55dcecf49f72ca1e24b7.png

3.1 当我们查询所有角色时,可以同时得到角色的所赋予的用户信息

一个Role可以赋予给多个User,因此在Role的实体类中包含User的集合引用:

public 

然后我们需要在IRoleDao.xml中定义封装role和user的一对多的resultMap:

<!--定义role表的ResultMap-->
<resultMap id="roleMap" type="role">
	<id property="roleId" column="rid"></id>
	<result property="roleName" column="role_name"></result>
	<result property="roleDesc" column="role_desc"></result>
	<collection property="users" ofType="user">
		<id property="userId" column="id"></id>
		<result property="userName" column="username"></result>
		<result property="userAddress" column="address"></result>
		<result property="userSex" column="sex"></result>
		<result property="userBirthday" column="birthday"></result>
	</collection>
</resultMap>

然后写查询语句:role先左关联user_role,再左关联user

<!--查询所有-->
<select id="findAll" resultMap="roleMap">
   select r.id as rid,r.role_name,r.role_desc,u.* from role r
   left outer join user_role ur  on r.id = ur.rid
   left outer join user u on U.ID = ur.uid
</select>

在测试类中测试:

/**

cf11afaba62335ec8caf5d3d4e96e22e.png

3.2 当我们查询所有用户时,可以同时得到用户所包含的角色信息

一个User可以有多个Role,因此在User的实体类中包含Role的集合引用:

public 

然后我们需要在IUserDao.xml中定义封装user和role的一对多的resultMap:

<!-- 定义User的resultMap-->
<resultMap id="userRoleMap" type="user">
	<id property="userId" column="id"></id>
	<result property="userName" column="username"></result>
	<result property="userAddress" column="address"></result>
	<result property="userSex" column="sex"></result>
	<result property="userBirthday" column="birthday"></result>
	<!-- 配置角色集合的映射 -->
	<collection property="roles" ofType="role">
		<id property="roleId" column="rid"></id>
		<result property="roleName" column="role_name"></result>
		<result property="roleDesc" column="role_desc"></result>
	</collection>
</resultMap>

然后写查询语句:user先左关联user_role,再左关联role

<!-- 查询所有 -->
<select id="findUserRole" resultMap="userRoleMap">
	select u.*,r.id as rid,r.role_name,r.role_desc from user u
	 left outer join user_role ur  on U.ID = ur.uid
	 left outer join role r on r.id = ur.rid
</select>

在测试类中测试:

/**
 * 测试多对多查询所有 user
 */
@Test
public void testFindUserRole(){
	List<User> users = userDao.findUserRole();
	for(User user : users){
		System.out.println("-----每个用户的信息------");
		System.out.println(user);
		System.out.println(user.getRoles());
	}
}

292e8cd502d70884906e615c06826af5.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值