准备工作
drop table if EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(16) NOT NULL COMMENT '用户名称',
`birthday` datetime DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
drop table if EXISTS `role`;
create table `role`(
`id` int not null comment '编号',
`role_name` varchar(30) default null comment '角色名称',
`role_desc` varchar(255) default null comment '角色描述',
primary key (`id`)
) ENGINE = INNODB DEFAULT CHARSET=utf8;
INSERT INTO `role` values (1,'院长','管理整个学院'),(2,'总裁','管理整个公司'),(3,'校长','管理整个学校');
select * FROM `role`
drop table if exists `user_role`;
create table `user_role`(
`uid` int not null comment '用户编号',
`rid` int not null comment '角色编号',
primary key(`uid`,`rid`),
CONSTRAINT foreign key(`rid`) REFERENCES `role`(`id`),
CONSTRAINT foreign key(`uid`) REFERENCES `user`(`id`)
) ENGINE = innodb default charset=utf8
INSERT INTO user_role values(1,1);
INSERT INTO user_role values(1,2);
INSERT INTO user_role values(1,3);
INSERT INTO user_role values(2,3);
- 一个用户可以有多个角色
- 一个角色可以赋予多个用户
- 用户和角色是多对多的关系
- 各自包含对方一个集合引用
- 当我们查询用户时,可以同时得到用户所包含的角色信息
- 当我们查询角色时,可以同时得到角色所属的用户信息
分析
select * from user u,role r,user_role ur where ur.uid = u.id and ur.rid = r.id
需求
查询所有角色,同时获取角色所赋予的用户,以角色为基准
select user.*,role.id as rid,role.role_name,role.role_desc
from role join user_role on role.id = user_role.rid
left join user on user.id = user_role.uidselect user.*,role.id as rid,role.role_name,role.role_desc
left join user_role on role.id = user_role.rid
left join user on user.id = user_role.uid
解决
Role.java实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private Integer roleId;
//用户名称
private String roleName;
//用户描述
private String roleDesc;
//一个角色包含多个用户
private List<User> users;
}
RoleDao.java接口
public interface RoleDao {
List<Role> findAll();
}
RoleDao.xml配置文件
<mapper namespace="com.kcl.dao.RoleDao">
<resultMap id="roleUserMap" type="com.kcl.pojo.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="com.kcl.pojo.User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<result property="birthday" column="birthday"></result>
</collection>
</resultMap>
<!--接口实现-->
<select id="findAll" resultType="com.kcl.pojo.Role" resultMap="roleUserMap">
select user.*,role.id as rid,role.role_name,role.role_desc from role join user_role on role.id = user_role.rid
left join user on user.id = user_role.uid
</select>
</mapper>
从用户到角色
也是同样子的道理,代码稍作改变就可以喽