<!--一对多,查询指定部门下所有职员信息-->
<mapper namespace="com.wry.pojo.Dept">
<select id="selectEmpByDeptNo" resultMap="empToDemp" resultType="dept">
SELECT d.deptno,d.dname,d.loc,e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm
FROM
t_dept d
LEFT JOIN
t_emp e
ON
d.deptno = e.deptno
</select>
<resultMap id="empToDemp" type="dept">
<!--数据行与乙方实体类关联的字段-->
<result column="deptno" property="deptNo"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
<!--设置数据行来自于多方表字段的存储方案-->
<!--ofType="xxx",collection指定字段内容保存在xxx对象中-->
<collection property="empList" ofType="emp">
<result column="empno" property="empNo"/>
<result column="ename" property="ename"/>
<result column="job" property="job"/>
<result column="sal" property="sal"/>
<result column="hiredate" property="hireDate"/>
</collection>
</resultMap>
</mapper>
@Test
public void testSelectEmpByDeptNo(){
SqlSession sqlSession = MyUtil.getSqlSession(true);
List<Dept> depts = sqlSession.selectList("com.wry.pojo.Dept.selectEmpByDeptNo");
depts.stream().forEach(dept -> {
System.out.println(dept);
});
}
多对一
SELECT * FROM emp JOIN dept ON emp.dept = dept.no WHERE job = 'saleasman'
-
- 多方实体类声明一个一方类型属性
- <assosication property="属性名" javaType="数据类型"></assosication>映射属性
<select id="selectAllEmp" resultType="emp" resultMap="emprs">
SELECTxxx。。。
</select>
<resultMap id="emprs" type="emp">
<result column="empno" property="empNo"/>
<!--设置数据行来自于一方表字段对应关系-->
<association property="dept" javaType="dept">
<result column="deptno" property="deptNo"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
</association>
</resultMap>
查询所有职员信息
<select id="selectAllEmp" resultType="emp" resultMap="emprs">
SELECT e.empno,e.ename,e.job,e.hiredate,e.sal,d.deptno,d.dname,d.loc
FROM
t_emp e
LEFT JOIN
t_dept d
ON
e.deptno = d.deptno
</select>
<resultMap id="emprs" type="emp">
<result column="empno" property="empNo"/>
<result column="ename" property="ename"/>
<result column="job" property="job"/>
<result column="hiredate" property="hireDate"/>
<result column="sal" property="sal"/>
<association property="dept" javaType="dept">
<result column="deptno" property="deptNo"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
</association>
</resultMap>
@Test
public void testSelectAllEmp(){
SqlSession sqlSession = MyUtil.getSqlSession(false);
List<Emp> emps = sqlSession.selectList("com.wry.pojo.Emp.selectAllEmp");
emps.stream().forEach(System.out::println);
}