日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時間:2025/3/21 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

<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的查詢結(jié)果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>

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。