工具类-老版hibernate 占位符模式(?) in 的问题解决方案

 

问题

  老版本的hibernate。在不允许 占位符、命名参数 公用模式下。

  以下sql情况,in 的模式是不生效的

     

select * from a where a in (?); 
//以上sql。传入list或者固定分隔符的字符串。实际测试均不生效
List params = new ArrayList(); 
params.add("aaa,bbb,ccc");

解决方案
  1、升级hibernate版本,使得 ? : 公用
  2、通过程序重新组装sql及参数。把  in(?) 变为 in(?,?,?,?) 参数并行做扩展

 

  

 以下程序即 方案2

package com.bytter.core.base;

import com.bytter.core.utils.EmptyUtils;
import com.bytter.core.utils.JsonUtils;

import java.util.*;

/**
 * @author zhouyy
 * @version 1.0
 * @description: TODO
 * @date 2022/6/10 18:05
 */
public class CommonUtils {
    /**
     * @description: 处理 ? 占位符的 in问题。 自动根据参数的list或者,分隔来 拼接 ?
     * @author zhouyy
     * @date: 2022/6/10 15:48
     */
    private static String excuteInSql(String sql, List params) {
        StringBuffer newSql = new StringBuffer();
        List newParams = new ArrayList();
        if(EmptyUtils.isNotEmpty(params)){
            String oldSql = sql;
            String[] sqlArray = oldSql.split("\\?");
            //key=下标 value=?,?,?
            Iterator iterator = params.iterator();
            int paramIndex = 0;
            while(iterator.hasNext()){
                Object obj = iterator.next();
                newSql.append(sqlArray[paramIndex]).append("?");
                //此参数是一个list
                System.out.println((obj != null && obj.toString().indexOf(",") > 0));
          //兼容 list、固定分隔符的字符串
if((obj instanceof Collection<?>) || (obj != null && obj.toString().indexOf(",") > 0)){ List list = (obj instanceof Collection<?>) ? (List)obj : Arrays.asList(obj.toString().replaceAll("'","").split(",")); int lengths = list.size(); //取当前参数所对应的sql的下标 int _sqlIndex = 0; for (int j = 0; j < sqlArray.length; j++) { //当前参数的下标 if(j == paramIndex){ for (int k = 0; k < lengths; k++) { if(k <lengths-1){ newSql.append(",?"); } //参数拆分并加入到参数list中 // params.add(paramIndex+k+1,list.get(k)); newParams.add(list.get(k)); } break; } } }else{ newParams.add(obj); } paramIndex ++; } newSql.append(sqlArray[sqlArray.length-1]); }else{ newSql.append(sql); } System.out.println(newSql.toString()); //對象轉json System.out.println(JsonUtils.toJSONString(newParams)); return newSql.toString(); } /** * @description: * @author zhouyy * @date: 2022/6/10 16:49 */ public static void main(String[] args) { // 首in 中? 中in 尾in // 首? 中in 尾in // String sql = "select * from aa where d=? "; // String sql = "select * from aa where d in (?) "; // String sql = "select * from aa where d in (?) and a=? "; // String sql = "select * from aa where d in (?) and a=? and c in (?) "; String sql = "select * from aa where a=? and c in (?) "; List params = new ArrayList(); params.add("1"); // params.add("011,012,013,014"); params.add("21,22,23,24,25"); // params.add("3"); excuteInSql(sql,params); } }

 

posted @ 2022-06-10 18:32  _万古如长夜  阅读(835)  评论(0编辑  收藏  举报