MyBatis框架
4.7 resultMap自定义映射
- 自定义resultMap,实现高级结果集映射
- id :用于完成主键值的映射
- result :用于完成普通列的映射
- association :一个复杂的类型关联;许多结果将包成这种类型
- collection : 复杂类型的集
4.7.1 id&result
<select id="getEmployeeById" resultMap="myEmp"> select id, last_name,email, gender from tbl_employee where id =#{id} </select> <resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmp"> <id column="id" property="id" /> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> </resultMap> |
4.7.2 association
- POJO中的属性可能会是一个对象,我们可以使用联合查询,并以级联属性的方式封装对象.使用association标签定义对象的封装规则
public class Department { private Integer id ; private String departmentName ; // 省略 get/set方法 } |
public class Employee { private Integer id ; private String lastName; private String email ; private String gender ; private Department dept ; // 省略 get/set方法 } |
- 使用级联的方式:
<select id="getEmployeeAndDept" resultMap="myEmpAndDept" > SELECT e.id eid, e.last_name, e.email,e.gender ,d.id did, d.dept_name FROM tbl_employee e , tbl_dept d WHERE e.d_id = d.id AND e.id = #{id} </select> <resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept"> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <!-- 级联的方式 --> <result column="did" property="dept.id"/> <result column="dept_name" property="dept.departmentName"/> </resultMap> |
- Association‘
<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept"> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <association property="dept" javaType="com.atguigu.mybatis.beans.Department"> <id column="did" property="id"/> <result column="dept_name" property="departmentName"/> </association> </resultMap> |