3、多对多
建立两张表:用户表,角色表
让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含各自的主键,在中间表中是外键。
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>
在测试类中测试:
/**
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());
}
}