1. 程式人生 > >Mybatis查詢結果ResultMap的繼承

Mybatis查詢結果ResultMap的繼承

需求:在查詢使用者表的同時,關聯角色表查出角色名稱(假設每個使用者只有一個角色)

//使用者類
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>