Mybatis 系列12-注解多对多
用户和角色是多对多的方式,在数据库上体现为,user表,role表和中间表user_role表
-- MySQL dump 10.13 Distrib 5.7.29, for Linux (x86_64)
-- ------------------------------------------------------
-- Server version 5.7.29
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) 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=56 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES (41,'update user clear cache','2018-02-27 17:47:08','男','??'),(42,'小二王','2013-03-04 11:34:34','女','杭州'),(43,'小二王','2013-03-04 11:34:34','女','杭州'),(45,'小李','2017-03-04 12:04:06','男','南京'),(46,'老王','2018-03-07 17:37:26','男','北京'),(48,'小宝','2018-03-08 11:44:00','女','上海'),(50,'小李','2011-01-05 00:00:00','男','你猜这是哪里'),(51,'小李','2011-01-05 00:00:00','女','中文输入'),(52,'小李','2011-01-05 00:00:00','女','江苏省'),(53,'小李','2011-01-05 00:00:00','男','江苏省南京市'),(54,'小李','2011-01-05 00:00:00','男','江苏省南京市'),(55,'张三','2011-01-05 00:00:00','男','江苏江宁');
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`ID` int(11) NOT NULL COMMENT '编号',
`ROLE_NAME` varchar(30) DEFAULT NULL COMMENT '角色名称',
`ROLE_DESC` varchar(60) DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `role` VALUES (1,'院长','管理整个学院'),(2,'总裁','管理整个公司'),(3,'校长','管理整个学校');
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`UID` int(11) NOT NULL COMMENT '用户编号',
`RID` int(11) NOT NULL COMMENT '角色编号',
PRIMARY KEY (`UID`,`RID`),
KEY `FK_Reference_10` (`RID`),
CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `role` (`ID`),
CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user_role` VALUES (41,1),(45,1),(41,2);
实体类User
package com.mantishell.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
private List<Role> roles;
public List<Role>getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
实体类Role
package com.mantishell.domain;
import java.io.Serializable;
import java.util.List;
public class Role implements Serializable {
private Integer roleId;
private String roleName;
private String roleDesc;
private List<User> users;
@Override
public String toString() {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
", users=" + users +
'}';
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
持久层接口:
IUserDao
package com.mantishell.dao;
import com.mantishell.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IUserDao {
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "sex", column = "sex"),
@Result(property = "roles", column = "id",many = @Many(
select = "com.mantishell.dao.IRoleDao.findRolesById",fetchType = FetchType.LAZY
))
})
List<User> findAll();
@Select("select * from user u inner join user_role ur on u.id=ur.uid where ur.rid=#{id}")
@ResultMap("userMap")
List<User> findUsersById(int id);
}
IRoleDao:
package com.mantishell.dao;
import com.mantishell.domain.Role;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IRoleDao {
@Select("select * from role")
@Results(id = "roleMap",value={
@Result(id=true,property = "roleId",column = "id"),
@Result(property = "roleName", column = "role_name"),
@Result(property = "roleDesc", column = "role_desc"),
@Result(property = "users", column = "id",many = @Many(
select = "com.mantishell.dao.IUserDao.findUsersById",fetchType = FetchType.LAZY //使用延迟加载
))
})
List<Role> findAll();
@Select("select * from role r inner join user_role ur on ur.rid=r.id where ur.uid=#{id}")
@ResultMap("roleMap")
List<Role> findRolesById(int id);
}
测试:
@Test
public void testAll() throws Exception{
List<User> users = userDao.findAll();
for (User user : users) {
List<Role> roles = user.getRoles();
if (roles.size() > 0) {
System.out.println(user);
System.out.println(user.getRoles());
}
}
}
查询结果:
测试角色:
@Test
public void testFindAll(){
List<Role> roles = roleDao.findAll();
List<User> users = null;
for (Role role : roles) {
users = role.getUsers();
if(users.size()> 0){
System.out.println(role);
System.out.println(users);
}
}
}