背景
之前因为业务应用写SQL查询数据不规范,可能查询10条也可能查询100条以及10W条,造成数据库IO流过大,以及大量数据返回应用中,造成应用宕机,领导要求查询数据量限制大小,从底层控制,遂查询各种资料终找到办法;
在mybatis拦截器中下手,代码比较简单,我就直接截图了:
其实只有一行吧,我们把参数中的RowBounds对象中的limit值改成设计需要的大小,则查询出来的数据就在这个范围内,这个是不限制数据库的,不管是oracle、mysql、sql server都可以使用。
让我们来分析一下RowBounds类:
public class RowBounds {
public static final int NO_ROW_OFFSET = 0;
public static final int NO_ROW_LIMIT = 2147483647;
public static final RowBounds DEFAULT = new RowBounds();
private int offset;
private int limit;
public RowBounds() {
this.offset = 0;
this.limit = 2147483647;
}
public RowBounds(int offset, int limit) {
this.offset = offset;
this.limit = limit;
}
public int getOffset() {
return this.offset;
}
public int getLimit() {
return this.limit;
}
}
RowBounds:默认初始化的大小是2147483647,相信各位同学不会忘记这个吧,这个值是int类型的最大值,多少来着? 好像是2的31次方吧!所以mybatis这里直接就放在int的最大值,我们只要把这个值改了,那么你想控制多少就多少。
java int 类整数的最大值是 2 的 31 次方 - 1 = 2147483648 - 1 = 2147483647