
最近在项目中使用between取不同的区间值问题,由于区间跨度大,而且区间多,又是前端传过来的参数,所以使用in和exists比较麻烦。然后就考虑使用between。现将使用方法记录一下。
假如表有个字段param_key,参数区间值为:100-300、1000-1999、3050-5000。
首先是between的用法是:param_key between value1 and value2。如果是有多个between则是:param_key between 100 and 300 and param_key between 1000 and 1999 and param_key between 3050 and 5000。
这杨很容易理解,也能很容易知道怎么写SQL,比较麻烦的就是我们使用的是Mybatis,所以拼接动态SQL和参数的传递方式很重要。
首先我们会想到使用mybatis的foreach去遍历。但是参数是param_key,所以就会想到把区间值给拆分成两部分来传递。具体作法如下:
1.首先创建一个类,用来封装区间值:
public class ParamKey{
private String startKey;
private String endKey; //getter,setter
}
2.创建请求类:
public class ParamRequest{
private List<ParamKey> key;//不同区间值的集合
private String operator;//1:取区间值,0:取反
private String code;//区间值代码
//getter,setter
}
3.业务处理:
public class ServiceImpl{ public void queryData( ParamRequest request){
//假如区间值是:100-200,3000-4500,5005-5020
request.setCode("[100-200],[3000-4500],[5005-5020]");
request.setOperator('1');
List<ParamKey> list = new ArrayList<>();
String code = request.getCode();
String [] aplit = code.split(",");
for( int i = 0 ; i ++ ; i < aplit.length){
ParamKey key = new ParamKey();
String [] param = aplit[i].split("-");
key.setStartKey(param[0].subString(1,param[0].length));
key.setEndKey(param[1].subString(0,param[1].length-1));
list.add(key);
}
request.setKey(list);
//业务处理,调用dao层方法
}
}
4.Mybatis中SQL:
<where>
1=1
<choose>
<when test="operator == 1">
and (
<!-- 取区间值 -->
<foreach collection="key" index="index" item="item" open="" separator="or" close="">
param_key between #{item.startKey} and #{item.endKey}
</foreach>
)
</when>
<when test="operator == 0">
and (
<!-- 取区间值之外的 -->
<foreach collection="param.codes" index="index" item="item" open="" separator="and" close="">
param_key not between #{item.startKey} and #{item.endKey}
</foreach>
)
</when>
</choose>
</where>