多对一也分为单条sql语句和多条sql语句
下面就以员工和就职部门为例:
员工实体类
private Integer empno;
private String empname;
private Integer deptno;
//植入部门实体
private Dept dept;
public Integer getEmpno() {return empno;}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {this.empname = empname;}
public Integer getDeptno() {return deptno;}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
部门实体类
private Integer deptno;
private String deptname;
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
单条sql语句
接口
/**
* 根据员工编号 获取员工姓名和所属部门
* 多对一 一条sal语句
* @param empno
* @return
*/
public Emp getEmpByEmpNo(int empno);
xml文件(小配置)
<!--根据员工编号 获取员工姓名和所属部门
多对一 一条sql语句
-->
<resultMap id="empMapper" type="Emp">
<id column="empno" property="empno"></id>
<result column="empname" property="empname"></result>
<association property="dept" javaType="Dept">
<id column="deptno" property="deptno"></id>
<result column="deptname" property="deptname"></result>
</association>
</resultMap>
<select id="getEmpByEmpNo" resultMap="empMapper">
SELECT dept.deptno,dept.deptname,empname,empno
FROM Dept,Emp
WHERE dept.deptno=emp.deptno AND empno=#{empno}
</select>
测试类
/**
* 根据员工编号 获取员工姓名和所属部门
* 多对一 一条sql语句
*/
@Test
public void getEmpByEmpNo(){
SqlSession session = MyBatisUtil.getSession();
IEmpDAO mapper = session.getMapper(IEmpDAO.class);
Emp emp = mapper.getEmpByEmpNo(1);
System.out.println(emp.getEmpname());
System.out.println(emp.getDept().getDeptname());
session.commit();
session.close();
}
多条sql语句
接口
/**
* 根据员工编号 获取员工姓名和所属部门
* 多对一 多条sal语句
* @param empno
* @return
*/
public Emp getEmpByEmpNoManySql(int empno);
xml文件(小配置)
<!--根据员工编号 获取员工姓名和所属部门
多对一 多条sql语句
-->
<resultMap id="empMapperMnaySql" type="Emp">
<id column="empno" property="empno"></id>
<result column="empname" property="empname"></result>
<association property="dept" javaType="Dept" column="empno" select="getEmpByEmpno"></association>
</resultMap>
<select id="getEmpByEmpno" resultType="Dept">
select *from dept where deptno=#{deptno}
</select>
<select id="getEmpByEmpNoManySql" resultMap="empMapperMnaySql">
SELECT empname,empno FROM Emp WHERE empno=#{empno}
</select>
测试类
/**
* 根据员工编号 获取员工姓名和所属部门
* 多对一 多条sql语句
*/
@Test
public void getEmpByEmpNoManySql(){
SqlSession session = MyBatisUtil.getSession();
IEmpDAO mapper = session.getMapper(IEmpDAO.class);
Emp emp = mapper.getEmpByEmpNoManySql(2);
System.out.println(emp.getEmpname());
System.out.println(emp.getDept().getDeptname());
session.commit();
session.close();
}