oracle数据库查询语句in后面的参数个数超过1000的处理方式

  • 在oracle中,使用in方法查询记录的时候,如果in后面的参数个数超过1000个,那么会发生错误,JDBC会抛出“java.sql.SQLException:ORA-01795: 列表中的最大表达式数为 1000”这个异常。比如执行select * from table where id in (1, 2, …, 1000, 1001, …..)时就会抛出上面的异常。
    下面用最简单粗暴的方式解决该问题:将超过的1000个参数进行or分割,如in (1,2,…1000) or in (1001,1002…)
import org.apache.commons.lang.StringUtils;
    /**
      * 创建 id 的in语句 如果ids为空则返回空字符串
      * @param ids
      * @param propertyStr(比较的属性)
      * @return
      */
     public static String createIdsInHqlAllowEmpty(String[] ids, String propertyStr) {
          if(ids.length<=1000){
              String idStr = createIds4Hql(ids);
              StringBuffer hqlBuffer = new StringBuffer("");
              if (StringUtils.isNotEmpty(idStr)) {
                   hqlBuffer.append(" and " + propertyStr + " in ").append(idStr);
              }
              return hqlBuffer.toString();
          }else{
              StringBuffer hqlBuffer = new StringBuffer("");
              hqlBuffer.append(" and ( ");
              int num = ids.length/1000;
              int remain = ids.length%1000;
              for(int i=0;i<=num;i++){
                   String[] newIds = null;
                   if(i!=num){
                        newIds = Arrays.copyOfRange(ids, i*1000, (i+1)*1000);
                   }else{
                        newIds = Arrays.copyOfRange(ids, i*1000, i*1000+remain);
                   }
                   String idStr = createIds4Hql(newIds);
                   if (StringUtils.isNotEmpty(idStr)) {
                        if(i==0){
                             hqlBuffer.append(propertyStr + " in ").append(idStr);
                        }else{
                             hqlBuffer.append(" or " + propertyStr + " in ").append(idStr);
                        }
                   }
              }
              hqlBuffer.append(")");
              return hqlBuffer.toString();
          }
     }
     /**
      * 创建ID集合字符串,供HQL使用
      * @param ids
      * @return
      */
     public static String createIds4Hql(String[] ids) {
          StringBuffer idBuffer = new StringBuffer("");
          String idsHql = null;
          StringBuffer hqlBuffer = new StringBuffer("");
          if (ids!=null&&ids.length>0) {
              for (String id : ids) {
                   idBuffer.append("'" + id + "',");
              }
              idsHql = StringUtils.substringBeforeLast(idBuffer.toString(), ",");
              hqlBuffer.append(" (").append(idsHql).append(")");
          }
          return hqlBuffer.toString();
     }

调用方式如:String sql = ‘select * from A o where 1=1 ‘+createIdsInHqlAllowEmpty(ids,”o.id”);
ids为id属性的条件集合。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值