日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

MyBatis使用ResultMap处理一对多多对一

發布時間:2025/3/21 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis使用ResultMap处理一对多多对一 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

出現下列情況:
員工表Emp和部門表Dept是多對一的關系,員工實體類中有Dept這個屬性,
但是多表連接查詢的時候只能查出Dept這張表的did和dname,無法和Dept這個屬性進行關聯,
此時若要查出員工信息表,那么Dept這個屬性會是null.
因此需要建立映射關系

方法一:連表查詢

<!-- 列名和屬性名一一對應 --><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"/><!-- 創建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

<resultMap type="Emp" id="map2"><id column="eid" property="eid"/><result column="ename" property="ename"/><result column="age" property="age"/><result column="gender" property="gender"/><!-- 將getAllEmp的查詢結果did賦值到getDeptByDid中 column:作為分步查詢的字段名--><association property="dept" select="getDeptByDid" column="did"></association></resultMap><select id="getAllEmp" resultType="map2">select ename,age,gender,did from emp where eid=#{eid}</select><select id="getDeptByDid" resultType="dept">select did,dname from dept where dept=#{did}</select>

總結

以上是生活随笔為你收集整理的MyBatis使用ResultMap处理一对多多对一的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。