当前位置:   article > 正文

mybatis解决<foreach>标签不能超过1000的问题_mybatis foreach最大限制

mybatis foreach最大限制

错误写法:

  1. <select id="getProductInfoList" resultType="vo">
  2. select a.name
  3. from A a
  4. where a.idin
  5. <foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
  6. #{item}
  7. </foreach>
  8. </select>

错误原因:

当<foreach>标签内的数量超过1000个时会提示一下报错:

java.sql.SQLSyntaxErrorException: ORA-01795: maximum number of expressions in a list is 1000

 

正确写法:

方案1(将传参变成SQL语句嵌套在SQL里面):

  1. <select id="getProductInfoList" resultType="vo">
  2. select a.name
  3. from A a
  4. where a.id in
  5. (select b.id from B b where b.id = #{billNo} and DELETED = 0)
  6. </select>

方案2(利用or每1000条添加一个or):

  1. SELECT
  2. *
  3. FROM
  4. ${tabNameMx} M
  5. WHERE
  6. M.CODE_ID IN
  7. <foreach collection="idList" index="index" open="(" close=")" item="id" separator=",">
  8. <if test="(index % 999) == 998"> NULL) OR M.CODE_ID IN(</if>#{id}
  9. </foreach>

这个SQL大家看着可能觉得有点懵逼,现在给你写段这段sql最终会变成什么样子,这样你瞬间就懂了。

SQL最终执行的样子:

CODE_ID IN('......','998',NULL ) OR M.CODE_ID IN('999',.....  NULL) OR M.CODE_ID IN('.....')

方案3(拼接OR ID IN ()):

  1. <select id="queryEnoByCapita">
  2. select t.custid,to_char(t.eno) as eno from T_E_ACCOUNT t where t.status !='2' and t.custid in
  3. <trim suffixOverrides=" OR t.custid in()">
  4. <foreach collection="capita" item="custId" index="index" open="(" close=")">
  5. <if test="index != 0">
  6. <choose>
  7. <when test="index % 1000 == 999">) OR t.custid in (</when>
  8. <otherwise>,</otherwise>
  9. </choose>
  10. </if>
  11. #{custId,jdbcType=VARCHAR}
  12. </foreach>
  13. </trim>
  14. </select>

分析:

  1. <trim>标签suffixOverrides:去掉后缀匹配上的东西,本例中后缀如果是 OR t.custid in()与suffixOverrides的属性值刚好匹配,则去掉 OR t.custid in()
  2. index 集合迭代的位置从0开始,为何需要<if test="index != 0">?如果没有,则sql是 t.cust in (,1,2..)会多一个逗号
  3. 没有999条数据的拼接SQL为:t.cust in (1,2..998)
  4. 超过999条的数据拼接SQL为:t.cust in (1,2..998) or t.custid in999,1000...1998) ...

拓展:

扩展1:foreach元素的属性主要有 item、index、 collection、open、separator、close

  1. collection foreach循环的对象
  2. item 集合中每一个元素或者该集合的对象,支持对象点属性的方式获取属性#{obj.filed} 或#{value}
  3. index 循环的下标,从0开始
  4. open 表示以什么开始
  5. separator 每次进行迭代之间以什么符号作为分隔符
  6. close表示以什么结束

扩展2:MyBatis trim 标签四个属性和其作用

  1. prefix 添加前缀
  2. prefixOverrides 删除前缀
  3. suffix 添加后缀
  4. suffixOverrides 删除后缀

参考链接:

myBatis大于1000的in查询解决办法 - 灰信网(软件开发博客聚合)

myBATIS foreach 达到 1000 的限制 |

mybatis中用where id in (),当数据大于1000条时可能出错问题解决 - 知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/749057
推荐阅读
相关标签
  

闽ICP备14008679号