mybatis中使用foreach in写法,sql中长度过长的解决方法

在sql语句中in后面参数的长度一般都有限制。
解决办事就是拆分,其实就是将select * from table where id in (。。超过1000。),改为select * from table where id in(少于1000)or id in(少于1000)

xml配置

<select id="">
        ...
        <if test="...">
            and
            <foreach collection="..." item="item" open="(" separator="or" close=")">
                b.program_id in
                <foreach collection="item" item="item2" open="(" separator="," close=")">
                    #{item2}
                </foreach>
            </foreach>
        </if>
        <if test="...">
            and 1=0
        </if>
        group by r.calculation_id,r.customer_id
    </select>

java大概代码

// 拆分数
private static final int splitNumber = 100;
// 所有的数据集
List<String> numberList = new ArrayList<String>();

// 拆分后的数据集
List<List<String>> agreementNumberList = new ArrayList<List<String>>();

int size = numberList.size();
int count = (size + splitNumber - 1) / splitNumber;
for (int i = 0; i < count; i++) {
    List<String> subList = numberList.subList(i * splitNumber, ((i + 1) * splitNumber > size ? size : splitNumber * (i + 1)));
    agreementNumberList.add(subList);
}

sql语句最后呈现形式

select r.* from ... r,.. b where 
( b.program_id in ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ) or b.program_id in ( ? , ? , ? , ? , ? , ? , ? , ? , ? ) ) group by r.calculation_id,r.customer_id 

你可能感兴趣的:(mybatis中使用foreach in写法,sql中长度过长的解决方法)