上一节我们
有Employee.java和Department.java
有EmployeeMapper.java和EmployeeMapper.xml
现在新增:DepartmentMapper.java和DepartmentMapper.xml
EmployeeMapper接口中有这么一个方法:
代码语言:javascript复制public Employee getEmpByIdStep(Integer id);
DepartmentMapper接口中有这么一个方法:
代码语言:javascript复制public Department getDeptById(Integer id);
DepartmentMapper.xml中:
代码语言:javascript复制<mapper namespace="com.gong.mybatis.dao.DepartmentMapper">
<select id="getDeptById" resultType="com.gong.mybatis.bean.Department">
select * from tbl_department where id=#{id}
</select>
</mapper>
EmployeeMapper.xml中
代码语言:javascript复制<mapper namespace="com.gong.mybatis.dao.EmployeeMapperPlus">
<resultMap type="com.gong.mybatis.bean.Employee" id="MySimpleByStep">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<association property="dept" select="com.gong.mybatis.dao.DepartmentMapper.getDeptById"
column="d_id">
</association>
</resultMap>
<select id="getEmpByIdStep" resultMap="MySimpleByStep">
select * from tbl_employee where id=#{id}
</select>
</mapper>
说明:我们直接对association中的属性进行操作。property属性还是指定所需要关联的Employee类中的成员属性的名称。select属性对应着DepartmentMapper.xml中的getDeptById方法。column属性对应着传入到该方法中的参数,由于tbl_employee中的d_id字段是和tbl_department中的Id字段相关联,我们可以传入d_id。
最后进行测试:
代码语言:javascript复制package com.gong.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.gong.mybatis.bean.Department;
import com.gong.mybatis.bean.Employee;
import com.gong.mybatis.dao.DepartmentMapper;
import com.gong.mybatis.dao.EmployeeMapperPlus;
public class TestMybatis2 {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(is);
}
@Test
public void test() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpByIdStep(3);
System.out.println(employee);
System.out.println(employee.getDept());
openSession.commit();
} finally {
openSession.close();
}
}
}
输出:
DEBUG 01-20 14:36:37,371 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145) DEBUG 01-20 14:36:37,413 ====> Preparing: select * from tbl_department where id=? (BaseJdbcLogger.java:145) DEBUG 01-20 14:36:37,414 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:145) DEBUG 01-20 14:36:37,418 <==== Total: 1 (BaseJdbcLogger.java:145) DEBUG 01-20 14:36:37,419 <== Total: 1 (BaseJdbcLogger.java:145) Employee [id=3, lastName=小红, gender=0, email=xiaohong@qq.com, dept=Department [id=1, deptName=开发部]] Department [id=1, deptName=开发部]
说明通过这种方式也是可以成功的。