1、建表语句
CREATE TABLE `user` (
`id` int(11) DEFAULT NULL,
`username` varchar(50) DEFAULT NULL
);
CREATE TABLE `role` (
`id` int(11) DEFAULT NULL,
`rolename` varchar(50) DEFAULT NULL,
`roledesc` varchar(50) DEFAULT NULL
);
CREATE TABLE `sys_user_role` (
`id` int(11) DEFAULT NULL,
`userid` int(11) DEFAULT NULL,
`roleid` int(11) DEFAULT NULL
);
2、实体
public class UserInfo {
private Integer id;
private String username;
private List<OrderInfo> orderInfoList;
private List<Role> roleList;
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 List<OrderInfo> getOrderInfoList() {
return orderInfoList;
}
public void setOrderInfoList(List<OrderInfo> orderInfoList) {
this.orderInfoList = orderInfoList;
}
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", orderInfoList=" + orderInfoList +
", roleList=" + roleList +
'}';
}
}
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
3、mapper.xml
<resultMap id="userRoleMap" type="com.deppon.domain.UserInfo">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<collection property="roleList" ofType="com.deppon.domain.Role">
<result property="id" column="id"></result>
<result property="roleName" column="rolename"></result>
<result property="roleDesc" column="roledesc"></result>
</collection>
</resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
select * from user u left join sys_user_role ur on u.id = ur.userid left join role r on r.id = ur.roleid;
</select>
4、测试类
public class TestOrderMapperUtil {
private UserMapper userMapper;
@Before
public void before() throws IOException {
String path = "SqlConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(path);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession(true);
userMapper = session.getMapper(UserMapper.class);
}
@Test
public void test(){
List<UserInfo> allUserAndRole = userMapper.findAllUserAndRole();
System.out.println(allUserAndRole);
}
}