1.先貼一個工具類OracleSQUtils,此類目的是爲了將數千個參數,按指定等分切片,最後用or進行拼接sql。
/**
* 將千條參數切成等分拼sql查詢,提高查詢效率
* @author Fantasy
*/
public class OracleSQUtils {
/**
* @param ids 存儲多個id的List集合
* @param count 將多個id按count切成等分拼接
* @param field 數據庫表對應字段
* @return 返回拼接語句 如 id in (1,2,3....1000) or id in (1001,1002,1003....2000) or ....
*/
public static String getOracleSQLIn(List<?> ids, int count, String field) {
count = Math.min(count, 1000);
int len = ids.size();
int size = len % count;
if (size == 0) {
size = len / count;
} else {
size = (len / count) + 1;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
int fromIndex = i * count;
int toIndex = Math.min(fromIndex + count, len);
//System.out.println(ids.subList(fromIndex, toIndex));
String productId = StringUtils.defaultIfEmpty(StringUtils.join(ids.subList(fromIndex, toIndex), "','"), "");
if (i != 0) {
builder.append(" or ");
}
builder.append(field).append(" in ('").append(productId).append("')");
}
return StringUtils.defaultIfEmpty(builder.toString(), field + " in ('')");
}
}
2.mybatis中sql的xml文件寫法配置:
<select id="querySomeInfoByIds" resultType="HashMap" parameterType="HashMap">
select dept_id,dept_name from dept a
where 1=1
<!--優化前:基於oracle數據庫做in查詢時,下面的通常寫法,當deptIds達到1000個以上時,oracle會報錯 -->
<if test="deptIds!= null">
AND a.DEPT_ID IN
<foreach item="item" index="index" collection="deptIds" open="(" separator="," close=")">
#{item}
</foreach>
</if>
<!-- 優化後:將傳入的多個id在業務代碼中按適當等分拼接好傳入mybatis文件中,提升查詢效率和避開超過1000個id時oracle數據庫拋異常 -->
and ( ${deptIds} )
<!-其它普通參數->
<if test="param!= null and param!= ''">
AND a.param =#{param}
</if>
....
</select>
3.業務代碼處理參數如下:
//deptIdList 中存儲數千個deptId
String deptIds=OracleSQUtils.getOracleSQLIn(deptIdList,1000,"a.DEPT_ID");
HashMap<String,Object> params=new HashMap<String,Object>();
params.put("deptIds",deptIds);
List<HashMap<String,Object>> resultList=deptService.querySomeInfoByIds(params);