1、使用association单步查询
1)、EmployeeMapper
package com.mi.dao;
import com.mi.pojo.Employee;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface EmployeeMapper {
public Employee getEmpAndDept(Integer id);
}
2)、EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mi.dao.EmployeeMapper">
<resultMap id="myEmpAndEmp2" type="com.mi.pojo.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<association property="dept" javaType="com.mi.pojo.Dept">
<result column="d_id" property="id"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<select id="getEmpAndDept" resultMap="myEmpAndEmp2">
select e.id,e.last_name, e.gender,d.id d_id,d.dept_name dept_name
from employee e ,dept d
where e.d_id = d.id and e.id = #{id}
</select>
</mapper>
3)、Test
@Test
public void getEmpAndDept() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpAndDept(3);
System.out.println(employee);
System.out.println(employee.getDept());