淺析Mybatis如何返回Map結構、@MapKey()的使用、返回List > 結構類型數據


一、Mybatis返回Map結構

// 使用Mybatis返回Map結構時,字段別名需要用雙引號包裹否則別名會全部小寫,沒有駝峰
<select id="selectById" resultType = "map"> 
    select id as "myId",name as "myName" from t_user </select>
// 對象則不用
<select id="selectById" resultType = "xxx.User"> 
    select id as myId,name as myName from t_user </select>

二、@MapKey()的使用

  這個注解是作用在方法上面的,具體的用法就是設置外面Map的KEY是什么。這樣我們就能夠查詢出非常復雜的結果,而不用在建立一個新的實體。

  希望mybatis返回以下Map格式數據:

{ "100": { "id": 100, "name": "小民", "age": 20 }, "101": { "id": 101, "name": "小白", "age": 20 } }
@MapKey("id") Map<Integer, StudentDO> groupById(); <select id="groupById" resultType="StudentDO">
    select * from student </select>

  即可達到上面的效果。

三、返回List<Map<K,V>> 結構類型數據

// dao層
List<Map<String, Object>> selectInviteRank(); // xml
<select id="selectInviteRank" resultMap="TestMap">
</select>

<resultMap id="TestMap" type="java.util.HashMap">
  <result column="userId" property="test1"></result>
  <result column="invites" property="invites"></result>
  <result column="account" property="account"></result>
  <result column="headImgUrl" property="headImgUrl"></result>
</resultMap>

  需要注意的是 userId 轉為了 test1,createdTime 的駝峰,如果沒在 resuleMap 里加的話,會變成小寫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM