mybatis解決<foreach>標簽不能超過1000的問題
更新時間:2024年05月01日 08:10:21 作者:小海海不怕困難
MyBatis是一個開源的持久層框架,它可以幫助開發(fā)者簡化數(shù)據(jù)庫操作的編寫,而foreach是MyBatis中的一個重要標簽,用于在SQL語句中進行循環(huán)操作,本文主要給大家介紹了mybatis解決<foreach>標簽不能超過1000的問題,需要的朋友可以參考下
錯誤寫法:
<select id="getProductInfoList" resultType="vo">
select a.name
from A a
where a.idin
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>錯誤原因:
當<foreach>標簽內的數(shù)量超過1000個時會提示一下報錯:
java.sql.SQLSyntaxErrorException: ORA-01795: maximum number of expressions in a list is 1000
正確寫法:
方案1(將傳參變成SQL語句嵌套在SQL里面):
<select id="getProductInfoList" resultType="vo">
select a.name
from A a
where a.id in
(select b.id from B b where b.id = #{billNo} and DELETED = 0)
</select>方案2(利用or每1000條添加一個or)
SELECT
*
FROM
${tabNameMx} M
WHERE
M.CODE_ID IN
<foreach collection="idList" index="index" open="(" close=")" item="id" separator=",">
<if test="(index % 999) == 998"> NULL) OR M.CODE_ID IN(</if>#{id}
</foreach>這個SQL大家看著可能覺得有點懵逼,現(xiàn)在給你寫段這段sql最終會變成什么樣子,這樣你瞬間就懂了。
SQL最終執(zhí)行的樣子:
CODE_ID IN('......','998',NULL ) OR M.CODE_ID IN('999',..... NULL) OR M.CODE_ID IN('.....')
方案3(拼接OR ID IN ()):
<select id="queryEnoByCapita">
select t.custid,to_char(t.eno) as eno from T_E_ACCOUNT t where t.status !='2' and t.custid in
<trim suffixOverrides=" OR t.custid in()">
<foreach collection="capita" item="custId" index="index" open="(" close=")">
<if test="index != 0">
<choose>
<when test="index % 1000 == 999">) OR t.custid in (</when>
<otherwise>,</otherwise>
</choose>
</if>
#{custId,jdbcType=VARCHAR}
</foreach>
</trim>
</select>分析:
<trim>標簽suffixOverrides:去掉后綴匹配上的東西,本例中后綴如果是 OR t.custid in()與suffixOverrides的屬性值剛好匹配,則去掉 OR t.custid in() index 集合迭代的位置從0開始,為何需要<if test="index != 0">?如果沒有,則sql是 t.cust in (,1,2..)會多一個逗號 沒有999條數(shù)據(jù)的拼接SQL為:t.cust in (1,2..998) 超過999條的數(shù)據(jù)拼接SQL為:t.cust in (1,2..998) or t.custid in(999,1000...1998) ...
拓展:
擴展1:foreach元素的屬性主要有 item、index、 collection、open、separator、close
collection foreach循環(huán)的對象
item 集合中每一個元素或者該集合的對象,支持對象點屬性的方式獲取屬性#{obj.filed} 或#{value}
index 循環(huán)的下標,從0開始
open 表示以什么開始
separator 每次進行迭代之間以什么符號作為分隔符
close表示以什么結束擴展2:MyBatis trim 標簽四個屬性和其作用
prefix 添加前綴 prefixOverrides 刪除前綴 suffix 添加后綴 suffixOverrides 刪除后綴
到此這篇關于mybatis解決<foreach>標簽不能超過1000的問題的文章就介紹到這了,更多相關mybatis foreach不能超過1000內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java commons io包實現(xiàn)多線程同步圖片下載入門教程
這篇文章主要介紹了Java commons io包實現(xiàn)多線程同步圖片下載入門,commons io: 是針對開發(fā)IO流功能的工具類庫,其中包含了許多可調用的函數(shù),感興趣的朋友跟隨小編一起看看吧2021-04-04

