美文网首页
mybatis的关联映射

mybatis的关联映射

作者: Apple_Boy | 来源:发表于2019-08-12 23:31 被阅读0次

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

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

    • 嵌套查询:通过执行另外一个SQL映射语句来返回关联数据结果(查2次)

    • 嵌套结果:执行一个表关联SQL查询,将结果映射成关联对象(查1次)

    嵌套查询:

    <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> 
    

    相关文章

      网友评论

          本文标题:mybatis的关联映射

          本文链接:https://www.haomeiwen.com/subject/wpqmjctx.html