修改emp类,去除外键属性deptno,添加部门对象信息作为属性
public class Emp {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Double sal;
private Double comm;
// private Integer deptno;
//添加Dept对象
private Dept dept;
public Emp() {
}
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Double sal, Double comm, Dept dept) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.dept = dept;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public Double getComm() {
return comm;
}
public void setComm(Double comm) {
this.comm = comm;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
Empmapper.java文件添加方法(这里遵循原则,从谁角度出发写在谁的接口里)
public interface EmpMapper {
List<Emp> findAll() throws Exception;
}
修改EmpMapper.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.msb.mapper.EmpMapper">
<!--id值和resultMap值对应,因为是在部门对象类型包含在员工类里,所以我们这里type属性为emp类的全限定名-->
<resultMap id="empAndDept" type="com.msb.pojo.Emp">
<!--id是主键映射,column是表里的类,property是对应实例类的属性值-->
<id column="empno" property="empno"></id>
<!--result表示其他列的映射-->
<result column="ename" property="ename"></result>
<result column="job" property="job"></result>
<association property="dept" javaType="com.msb.pojo.Dept">
<id column="deptno" property="deptno"></id>
<result column="dname" property="dname"></result>
<result column="loc" property="loc"></result>
</association>
</resultMap>
<select id="findAll" resultMap="empAndDept">
select e.empno,e.ename,e.job,e.deptno,d.dname,d.loc from emp e inner join dept d on e.deptno = d.deptno
</select>
</mapper>
测试类
@Test
public void test1() throws Exception {
SqlSession sqlSession = factory.openSession();
//传入参数为想获得接口的实现类
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
List<Emp> all = mapper.findAll();
for(Emp e:all){
System.out.println(e.getEname() + ";" + e.getJob() + ";"
+ e.getDept().getDeptno() + ";" + e.getDept().getDname() + ";" + e.getDept().getLoc());
}
sqlSession.close();
}
运行结果