mybatis將物件引數轉臨時表join
阿新 • • 發佈:2018-12-20
- 起因
同事業務需求要將陣列物件用到sql中join,想將其轉換為臨時表方便使用。需要將兩張表相除的結果進行排序和分頁,如果能在sql裡完成將會方便很多。
- 思路
sql 的 select 可以指定常量,當然就包括物件裡面的資料。所以根據 mybatis 語法我們可以直接select #{欄位名1} as amount,#{欄位名2} as store_code
就可以轉換這個物件,那麼問題又來了,物件如果是陣列了,怎麼才能實現多行了?如果熟悉sql語法的同學會知道union
這個操作,對,我們用union
可以連多行資料,就像這樣:
select 10.00 as amount,'X031' as store_code union select 20.00 as amount,'D033' as store_code
就會得到2行資料,那麼多行用如何在mybatis中實現了,這時很容易就想到我們的foreach
了。當然這種方式適合的資料量是有限的。
- 樣例
select sd.daily_init_target_money / tmp.reality_money as targetImplRate, tmp.reality_money as salesAmount, sd.store_code from store_daily_sales_analyze sd join ( <foreach collection="storeTargetDtoListList" item="storeTargetDtoListItem" index="index" separator="union"> select #{storeTargetDtoListItem.storeCode} as store_code, #{storeTargetDtoListItem.salesAmount} as reality_money </foreach> )tmp on tmp.store_code = sd.store_code <where> <include refid="query_whereConditions"/> </where>```