自定义结果映射规则
<resultMap type="entity.Employee" id="getEmpByIdMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="email" property="email"/>
resultMap>
<select id="getEmpById" resultMap="getEmpByIdMap">
select * from employee where id=#{id}
select>
association联合查询
association可以指定联合的javabean对象
property="dept":指定哪个属性是联合对象
javaType:指定这个属性的类型
<resultMap type="entity.Employee" id="getEmpAndDeptMap">
<id column="id" property="id"/>
<result column="empName" property="name"/>
<result column="sex" property="sex"/>
<result column="email" property="email"/>
<association property="dept" javaType="entity.Department">
<id column="did" property="id"/>
<result column="deptName" property="departmentName"/>
association>
resultMap>
<select id="getEmpAndDept" resultMap="getEmpAndDeptMap">
select e.id id,e.name empName,e.email email,e.sex sex,e.d_id d_id,
d.id did,d.name deptName from employee e,dept d
where e.d_id=d.id and e.id=#{id}
select>
使用association进行分布查询
1、先按照员工id查询员工信息将会调用查询员工的sql
2、根据查询员工信息中的d_id值去部门表中查出部门信息
3、部门设置到员工中
<resultMap type="entity.Employee" id="getEmpAndDeptStepMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="email" property="email"/>
<discriminator javaType="string" column="sex">
<case value="男" resultType="entity.Employee">
<association property="dept" select="dao.DepartmentMapper.getDeptById"
column="d_id">
association>
case>
discriminator>
resultMap>
<select id="getEmpByIdStep" resultMap="getEmpAndDeptStepMap">
select * from employee where id=#{id}
select>
嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则
<resultMap type="entity.Department" id="getDeptByIdPlusMap">
<id column="did" property="id"/>
<result column="deptName" property="departmentName"/>
<collection property="emps" ofType="entity.Employee">
<id column="eid" property="id"/>
<result column="empName" property="name"/>
<result column="sex" property="sex"/>
<result column="email" property="email"/>
collection>
resultMap>
<select id="getDeptByIdPlus" resultMap="getDeptByIdPlusMap">
select d.id did,d.name deptName,e.id eid,
e.name empName,e.sex,e.email
from dept d left join employee e
on d.id=e.d_id
where d.id=#{id}
select>
collection分步查询
<resultMap type="entity.Department" id="getDeptByIdStepMap">
<id column="id" property="id"/>
<result column="name" property="departmentName"/>
<collection property="emps" select="dao.EmployeeMapperPlus.getEmpsByDeptId"
column="{id}">
collection>
resultMap>
<select id="getEmpsByDeptId" resultType="entity.Employee">
select * from employee where d_id=#{deptId}
select>
<select id="getDeptByIdStep" resultMap="getDeptByIdStepMap">
select * from dept where id=#{id}
select>
当分布查询需要传递多个多个值时,将多个值封装map传递
colum=“{key1=column1,key2=colum2...}”