sqlserver2005的分页优化
这篇文章主要介绍“sqlserver2005的分页优化”,在日常操作中,相信很多人在sqlserver2005的分页优化问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”sqlserver2005的分页优化”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
一、hibernate分页 hibernate对MsSql的伪分页
分页是web项目中比不可少的一个功能,数据量大的时候不能全部展示必然要用到分页技术。相信大家对hibernate中的分页都不陌生:
Java代码
public Query setMaxResults(int maxResults);
public Query setFirstResult(int firstResult);
Java代码
public Query setMaxResults(int maxResults);
public Query setFirstResult(int firstResult);
只要调用了这两个方法并设置好参数,hibernate自动分页完全屏蔽了底层分页技术,这也是众多开发者喜欢hibernate的原因之一。
项目开发中遇到一个奇怪的问题。数据库采用的是Sql Server 2005,也设置了上面两个参数,可是每次发送到数据库端的SQL语句都是select top ....语句。即便是查询第10w条,也只有一个select top 语句,不免引起对hibernate实现sql server分页的怀疑。hibernate针对不同数据库实现的分页方法封装在对应数据库的方言里,通过getLimitString方法转化成对应数据库的分页算法。
以常见的Mysql数据库的方言MySQLDialect为例:
Java代码
public String getLimitString(String sql, boolean hasOffset) {
return new StringBuffer( sql.length() + 20 )
.append( sql )
.append( hasOffset ? " limit ?, ?" : " limit ?" )
.toString();
}
Java代码
public String getLimitString(String sql, boolean hasOffset) {
return new StringBuffer( sql.length() + 20 )
.append( sql )
.append( hasOffset ? " limit ?, ?" : " limit ?" )
.toString();
}
采用了大家熟悉的的limit进行分页。
数据库的方言Oracle9iDialect:
Java代码
StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
if (hasOffset) {
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
}
else {
pagingSelect.append("select * from ( ");
}
pagingSelect.append(sql);
if (hasOffset) {
pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
}
else {
pagingSelect.append(" ) where rownum <= ?");
}
Java代码
StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
if (hasOffset) {
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
}
else {
pagingSelect.append("select * from ( ");
}
pagingSelect.append(sql);
if (hasOffset) {
pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
}
else {
pagingSelect.append(" ) where rownum <= ?");
}
利用Oracle的rownum 结合三层嵌套查询完成分页。这个三层是Oracle最经典高效的分页算法。
可是针对Sql Server的方言SQLServerDialect:
Java代码
public String getLimitString(String querySelect, int offset, int limit) {
if ( offset > 0 ) {
throw new UnsupportedOperationException( "query result offset is not supported" );
}
return new StringBuffer( querySelect.length() + 8 )
.append( querySelect )
.insert( getAfterSelectInsertPoint( querySelect ), " top " + limit )
.toString();
}
Java代码
public String getLimitString(String querySelect, int offset, int limit) {
if ( offset > 0 ) {
throw new UnsupportedOperationException( "query result offset is not supported" );
}
return new StringBuffer( querySelect.length() + 8 )
.append( querySelect )
.insert( getAfterSelectInsertPoint( querySelect ), " top " + limit )
.toString();
}
揉揉眼睛、再揉揉,没错,只出现了一个top语句。这就意味着如果查询第10w页的数据,需要把前10w页数据全部提取出来。hibernate针对sql server的分页是伪分页,所以随着数据量日益增加用户抱怨系统速度慢,程序员抱怨hibernate性能低,dba抱怨开发人员sql功底太浅。
不知道hibernate开发组,出于什么目前或情况没有真正提供sql server的分页技术,那我们自己来实现。
方言类:
Java代码
public class SQLServer2005Dialect extends SQLServerDialect {
private ThreadLocal<Boolean> supportsVariableLimit = new ThreadLocal<Boolean>();
public SQLServer2005Dialect() {
registerFunction("bitand", new BitAndFunction());
registerFunction("bitxor", new BitXorFunction());
registerFunction("bitor", new BitOrFunction());
setSupportsVariableLimit(false);
}
private void setSupportsVariableLimit(boolean first) {
this.supportsVariableLimit.set(Boolean.valueOf(first));
}
protected static int getSqlAfterSelectInsertPoint(String sql) {
int selectIndex = sql.toLowerCase().indexOf("select");
int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
return selectIndex + ((selectDistinctIndex == selectIndex) ? 15 : 6);
}
public boolean supportsLimitOffset() {
return true;
}
public boolean supportsVariableLimit() {
return ((Boolean) this.supportsVariableLimit.get()).booleanValue();
}
public boolean useMaxForLimit() {
return true;
}
public String getLimitString(String query, int offset, int limit) {
setSupportsVariableLimit(offset > 0);
if (offset == 0) {
return new StringBuffer(query.length() + 8).append(query).insert(
getSqlAfterSelectInsertPoint(query), " top " + limit)
.toString();
}
return getLimitString(query, offset > 0);
}
public String getLimitString(String sql, boolean hasOffset) {
int orderByIndex = sql.toLowerCase().lastIndexOf("order by");
if (orderByIndex <= 0) {
throw new UnsupportedOperationException(
"must specify 'order by' statement to support limit operation with offset in sql server 2005");
}
String sqlOrderBy = sql.substring(orderByIndex + 8);
String sqlRemoveOrderBy = sql.substring(0, orderByIndex);
int insertPoint = getSqlAfterSelectInsertPoint(sql);
return new StringBuffer(sql.length() + 100)
.append("with tempPagination as(")
.append(sqlRemoveOrderBy)
.insert(
insertPoint + 23,
" ROW_NUMBER() OVER(ORDER BY " + sqlOrderBy
+ ") as RowNumber,")
.append(
") select * from tempPagination where RowNumber>? and RowNumber<=?")
.toString();
}
}
Java代码
public class SQLServer2005Dialect extends SQLServerDialect {
private ThreadLocal<Boolean> supportsVariableLimit = new ThreadLocal<Boolean>();
public SQLServer2005Dialect() {
registerFunction("bitand", new BitAndFunction());
registerFunction("bitxor", new BitXorFunction());
registerFunction("bitor", new BitOrFunction());
setSupportsVariableLimit(false);
}
private void setSupportsVariableLimit(boolean first) {
this.supportsVariableLimit.set(Boolean.valueOf(first));
}
protected static int getSqlAfterSelectInsertPoint(String sql) {
int selectIndex = sql.toLowerCase().indexOf("select");
int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
return selectIndex + ((selectDistinctIndex == selectIndex) ? 15 : 6);
}
public boolean supportsLimitOffset() {
return true;
}
public boolean supportsVariableLimit() {
return ((Boolean) this.supportsVariableLimit.get()).booleanValue();
}
public boolean useMaxForLimit() {
return true;
}
public String getLimitString(String query, int offset, int limit) {
setSupportsVariableLimit(offset > 0);
if (offset == 0) {
return new StringBuffer(query.length() + 8).append(query).insert(
getSqlAfterSelectInsertPoint(query), " top " + limit)
.toString();
}
return getLimitString(query, offset > 0);
}
public String getLimitString(String sql, boolean hasOffset) {
int orderByIndex = sql.toLowerCase().lastIndexOf("order by");
if (orderByIndex <= 0) {
throw new UnsupportedOperationException(
"must specify 'order by' statement to support limit operation with offset in sql server 2005");
}
String sqlOrderBy = sql.substring(orderByIndex + 8);
String sqlRemoveOrderBy = sql.substring(0, orderByIndex);
int insertPoint = getSqlAfterSelectInsertPoint(sql);
return new StringBuffer(sql.length() + 100)
.append("with tempPagination as(")
.append(sqlRemoveOrderBy)
.insert(
insertPoint + 23,
" ROW_NUMBER() OVER(ORDER BY " + sqlOrderBy
+ ") as RowNumber,")
.append(
") select * from tempPagination where RowNumber>? and RowNumber<=?")
.toString();
}
}
函数:
Java代码
public class BitAndFunction implements SQLFunction {
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
public String render(List args, SessionFactoryImplementor factory)
throws QueryException {
if (args.size() != 2) {
throw new IllegalArgumentException(
"BitAndFunction requires 2 arguments!");
}
return args.get(0).toString() + " & " + args.get(1).toString();
}
}
Java代码
public class BitAndFunction implements SQLFunction {
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
public String render(List args, SessionFactoryImplementor factory)
throws QueryException {
if (args.size() != 2) {
throw new IllegalArgumentException(
"BitAndFunction requires 2 arguments!");
}
return args.get(0).toString() + " & " + args.get(1).toString();
}
}
Java代码
public class BitOrFunction implements SQLFunction {
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
public String render(List args, SessionFactoryImplementor factory)
throws QueryException {
if (args.size() != 2) {
throw new IllegalArgumentException(
"BitOrFunction requires 2 arguments!");
}
return args.get(0).toString() + " | " + args.get(1).toString();
}
}
Java代码
public class BitOrFunction implements SQLFunction {
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
public String render(List args, SessionFactoryImplementor factory)
throws QueryException {
if (args.size() != 2) {
throw new IllegalArgumentException(
"BitOrFunction requires 2 arguments!");
}
return args.get(0).toString() + " | " + args.get(1).toString();
}
}
Java代码
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
public String render(List args, SessionFactoryImplementor factory)
throws QueryException {
if (args.size() != 2) {
throw new IllegalArgumentException(
"BitXorFunction requires 2 arguments!");
}
return args.get(0).toString() + " ^ " + args.get(1).toString();
}
到此,关于“sqlserver2005的分页优化”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341