1. 问题说明
-- 类似这种 SQL SELECT * FROM tableName WHERE tableField IN ('','')
姑且不说这种 SQL 的效率和可优化和替代性,就当前问题在 MySQL、Greenplum 数据库没有 1000 的限制。
2. 解决方法
解决的方法较多,这里使用的是 JDK8 的 stream 方法,代码如下:
/** * 通过 List 数据获取 inStr 字符串(超过 1000 个改成 or in) * * @param list List对象 * @return inStr 字符串 */ private String getInStrByList(List<Map<String, Object>> list) { int listSize = list.size(); List<Map<String, Object>> tempRecordList; // 分段大小(这个数值可以写成参数传递过来) int lengthControl = 1000; List<String> inStrSegmentList = new ArrayList<>(); if (listSize <= lengthControl) { return list.stream().map(oneMap-> MapUtils.getString(oneMap, "fieldName")).collect(Collectors.joining("','", " table_field in ( '", "' ) ")); } else { // 进行分段 double number = listSize * 1.0 / lengthControl; int n = ((Double) Math.ceil(number)).intValue(); for (int i = 0; i < n; i++) { int iLength = i * lengthControl; int end = lengthControl * (i + 1); if (end > listSize) { end = listSize; } tempRecordList = list.subList(iLength, end); String inStrSegment = tempRecordList.stream().map(oneMap -> MapUtils.getString(oneMap, "fieldName")).collect(Collectors.joining("','", "'", "'")); inStrSegmentList.add(inStrSegment); } } return inStrSegmentList.stream().collect(Collectors.joining(" ) or table_field in ( "," ( table_field in ( "," ) )")); }
字符串的使用举例:
<select id="geDataList" parameterType="java.util.Map" resultType="java.util.Map"> SELECT * FROM table_name <where> <if test="inStr != null and inStr != ''"> AND ${inStr} </if> </where> </select>