以問題推動學習之——Mybatis(1)
阿新 • • 發佈:2018-12-13
以問題推動學習之——Mybatis(1)
collection
需求
將上表中相同to_platform對應的flow_record_cnt變成ArrayList,如下表所示。
解決
由於mybatis沒有ArrayList型別,因此選用collection進行聚合。
<resultMap id="test" type="TbPlatformFlowStatsDO"> <id column="to_platform" jdbcType="VARCHAR" property="toPlatform" /> <collection property="test" javaType="ArrayList" jdbcType="BIGINT" ofType="Long"> <id column="flow_record_cnt" jdbcType="BIGINT" property="flowRecordCnt" /> </collection> </resultMap> <select id="selectTest" resultMap="test"> select to_platform, flow_record_cnt from tb_platform_flow_stats ; </select>
結果如下圖:
深入理解
再次回看上述程式碼,可以發現<id column=“to_platform” jdbcType=“VARCHAR” property=“toPlatform”//>與collection中的<id column=“flow_record_cnt” jdbcType=“BIGINT” property=“flowRecordCnt” //>,自動帶有聚合能力,相同的to_platform會聚合成為一組,對應的flow_record_cnt可以變為ArrayList型別。
但在這裡需要注意2點:
- 只有result中的id行與collection中的id行可以聚合,換句話說,如果在to_platform下增加了一個id行,那麼這就是聯合聚合(同時滿足這兩個條件,才將collection的值放在一個ArrayList中),但是如果這一行不是id,而是result,那麼這一行不會和第一行聯合聚合,它的值如果不唯一,那麼你可能獲取的值是隨機的(一般是第一行的值,需要注意)。
<resultMap id="test" type="TbPlatformFlowStatsDO"> <id column="to_platform" jdbcType="VARCHAR" property="toPlatform" /> <id(result) column="stat_time" jdbcType="VARCHAR" property="statTime" /> <collection property="test" javaType="ArrayList" jdbcType="BIGINT" ofType="Long"> <id column="flow_record_cnt" jdbcType="BIGINT" property="flowRecordCnt" /> </collection> </resultMap>
- 自定義類
如果你想自定義collection類,那麼將ofType中的值改為自定義的類即可,不過你需要注意的是,這個自定義類需要是public類,不然沒法呼叫。
具體的操作可以檢視mybatis xml的對映操作