mybatis的关联映射

2019-08-12  本文已影响0人  Apple_Boy

在查询时经常需要获取两个或两个以上关联表的数据,通过关联映射可以由一个对象获取相关联对象的数据。例如查询一个Emp员工对象,可以通过关联映射获取员工所在部门的Dept对象信息。

MyBatis的关联映射有以下两种不同的表现形式:

嵌套查询:

<select id="findById" parameterType="java.lang.Integer" resultMap= "empMap">
   select * from EMP where EMPNO=#{id}
</select>

<select id="selectDept" parameterType="java.lang.Integer" resultType="Dept">
   select * from DEPT where DEPTNO=#{id}
</select>

<resultMap type="Emp" id="empMap">
   <association property="dept" column="DEPTNO" javaType="Dept"     select="selectDept">
   </association>
</resultMap>

当利用findById查询EMP时,只会查询EMP表返回一个Emp对象,当访问Emp对象的dept属性时,会调用selectDept查询操作获取DEPT表相关的记录

嵌套结果:

<select id="findById" parameterType="java.lang.Integer" resultMap= "empMap">
    select  e.empno,e.ename,e.job,e.mgr,e.sal,e.comm,e.hiredate,e.deptno,
    d.dname,d.loc from EMP e join DEPT d on(d.deptno=e.deptno)
    where e.EMPNO=#{id}
</select>

<resultMap type="Emp" id="empMap">
   <id property="empno" column="EMPNO" />
   <result property="ename" column="ENAME" />
   <result property="job" column="JOB" />
   <result property="mgr" column="MGR" />
   ...
   <association property="dept" column="DEPTNO" javaType="Dept">
   <id...
   <result...
   </association>
</resultMap> 
上一篇下一篇

猜你喜欢

热点阅读