先增加两个方法,在查询的时候没有部门的名字,因此添加方法来查询的时候把部门的名字一起返回。
先在dao/EmployeeMapper中添加两个接口:
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
再在bean/Employee中添加部门变量和get以及set方法:
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
返回到EmployeeMapper.xml中,先添加一个自己定义的ResultMap,封装返回带有部门信息的
<resultMap id="WithDeptResultMap" type="zxf.bean.Employee">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<association property="department" javaType="zxf.bean.Department">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>```
在添加这两个查询带有部门信息的方法:
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
</sql>
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
FROM tbl_emp e
LEFT JOIN tbl_dept d ON e.`d_id` = d.`dept_id`
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
FROM tbl_emp e
LEFT JOIN tbl_dept d ON e.`d_id` = d.`dept_id`
where emp_id = #{empId,jdbcType=INTEGER}
</select>