MyBatis使用ResultMap处理一对多多对一
生活随笔
收集整理的這篇文章主要介紹了
MyBatis使用ResultMap处理一对多多对一
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
出現(xiàn)下列情況:
員工表Emp和部門表Dept是多對一的關(guān)系,員工實體類中有Dept這個屬性,
但是多表連接查詢的時候只能查出Dept這張表的did和dname,無法和Dept這個屬性進行關(guān)聯(lián),
此時若要查出員工信息表,那么Dept這個屬性會是null.
因此需要建立映射關(guān)系
方法一:連表查詢
<!-- 列名和屬性名一一對應(yīng) --><resultMap type="Emp" id="map1"><id column="eid" property="eid"/><result column="ename" property="ename"/><result column="age" property="age"/><result column="gender" property="gender"/><!-- 創(chuàng)建Dept對象后,賦值給Emp類中的dept屬性 --><association javaType="Dept" property="dept" ><id column="did" property="did"/><result column="dname" property="dname"/> </association> </resultMap><select id="getAllEmpWithDept" resultMap="map1">select eid,ename,age,gender,did,dname from Emp e left join Dept d on e.did=d.did </select>方法二:分步查詢
①先通過eid查詢到ename,age,gender,did字段
②通過查詢出來的did字段,再查詢出Dept表中的dname
總結(jié)
以上是生活随笔為你收集整理的MyBatis使用ResultMap处理一对多多对一的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis执行过程源码分析
- 下一篇: 解决MAVEN项目不扫描src下的map