需求:在查询用户表的同时,关联角色表查出角色名称(假设每个用户只有一个角色)
//用户类
public class User {
private String id;
private String name;
private String roleId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
}
//角色类
public class Role {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//接收查询结果的用户类
public class UserView extends User{
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName= roleName;
}
}
XML文件
<resultMap id="BaseResultMap" type="User" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="role_id" property="roleId" jdbcType="VARCHAR" />
</resultMap>
<resultMap id="ViewMap" type="UserView" extends="BaseResultMap">
<result column="role_name" property="roleName" jdbcType="VARCHAR" />
</resultMap>
<select id="queryList" resultMap="ViewMap" parameterType="UserView">
select
u.id,
u.name,
u.role_id,
r.name as role_name
from user u
left join role r
on u.role_id = r.id
</select>