您的位置:首页 > 其它

Mybatis的关联映射

2018-04-09 09:26 246 查看
通过员工ID找到员工,并得到他的部门信息public class Emp {
private int empno;
private String ename;
private double sal;
private int deptno;
Dept dept;

public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.test.dao.EmpDao">

<select id="findEmpById" parameterType="java.lang.Integer" resultMap="empMap">
SELECT * from emp join dept on emp.deptno=dept.deptno where emp.empno =#{id}
</select>

<resultMap type="com.test.entity.Emp" id="empMap">
<id property="empno" column="empno"/>
<result property="ename" column="ename"/>
<result property="sal" column="sal"/>
<association property="dept" column="deptno" javaType="com.test.entity.Dept">
<id property="deptno" column="deptno"/>
<result property="dname" column="dname"/>
<result property="loc" column="loc"/>
</association>
</resultMap>

</mapper>
通过部门ID找到部门,并得到该部门员工的信息public class Dept {
private int deptno;
private String dname;
private String loc;
private List<Emp> emps;

public List<Emp> getEmps() {
return emps;
}
public void setEmps(List<Emp> emps) {
this.emps = emps;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.test.dao.DeptDao">
<select id="findByDeptId" parameterType="java.lang.Integer" resultMap="deptMap">
select * from dept join emp on dept.deptno=emp.deptno where dept.deptno = #{id}
</select>

<resultMap type="com.test.entity.Dept" id="deptMap">
<id property="deptno" column="deptno"/>
<result property="dname" column="dname" jdbcType="VARCHAR" javaType="string"/>
<result property="loc" column="loc"	jdbcType="VARCHAR" javaType="string"/>
<collection property="emps" ofType="com.test.entity.Emp" javaType="java.util.ArrayList" column="deptno">
<id property="empno" column="empno"/>
<result property="ename" column="ename"/>
<result property="sal" column="sal"/>
<result property="deptno" column="deptno"/>
</collection>
</resultMap>
</mapper>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: