Hibernate中SQLServer2005方言(支援真分頁)
阿新 • • 發佈:2019-02-02
由於Hibernate中預設的SQL Server方言不支援真分頁,在兩者結合的時候總會覺得有那麼一點不和諧。Oracle提供了rownum,MySQL也有limit和offset,但是SQL Server只有top,所以Hibernate採用的策略是將每頁條數*頁碼的資料使用top全部載入進來再在記憶體中進行假分頁的處理。不過SQL Server 2005以上版本微軟已經提供了ROWNUMBER()的支援,所以有必要對方言進行改進以提升效能,另外也簡單地加了幾個函式。
/** * <p>SQL Server 2005方言。</p> * <pre> * 1.支援SQL Server 2005版本,不支援SQL Server 2000及以前版本 * 2.支援真分頁,第一頁採用top查詢,其餘採用ROW_NUMBER()實現。第一頁以上查詢要求sql中必須含有排序子句 * </pre> * @author Reker * <p>2008-6-11</p> */ public class SQLServer2005Dialect extends CustomSQLDialect { /** * 建構函式。 */ public SQLServer2005Dialect() { super(); registerFunction("bitand", new BitAndFunction()); registerFunction("bitxor", new BitXorFunction()); registerFunction("bitor", new BitOrFunction()); setSupportsVariableLimit(false); } /** * 是否需要繫結limit引數? * 在SQL Server中使用top時不能使用引數表示top條數,而使用ROW_NUMBER()則需要提供limit引數 */ private ThreadLocal<Boolean> supportsVariableLimit = new ThreadLocal<Boolean>(); /** * <p>設定是否先繫結limit引數。</p> * @author Reker * @param first */ private void setSupportsVariableLimit(boolean first) { supportsVariableLimit.set(first); } /** * <p>獲取sql中select子句位置。</p> * @author Reker * @param sql * @return int */ protected static int getSqlAfterSelectInsertPoint(String sql) { int selectIndex = sql.toLowerCase().indexOf("select"); final int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct"); return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6); } /* * @author Reker * <code>SQLServerDialect<code>中supportsLimit為true, * 但supportLimitOffset和supportsVariableLimit為false */ public boolean supportsLimitOffset() { return true; } /* * @author Reker * @see org.hibernate.loader.Loader#bindLimitParameters(PreparedStatement ,int ,RowSelection) * Hibernate在獲得Limit String(已添加了limit子句)後,如果此方法返回true, * 則會新增額外的引數值(ROW_NUMBER()範圍)(策略可能是這樣:有offset設定兩個引數值,沒有設定一個引數值) */ public boolean supportsVariableLimit() { return supportsVariableLimit.get(); } /* * @author Reker * @see org.hibernate.loader.Loader#getMaxOrLimit(RowSelection,Dialect) */ public boolean useMaxForLimit() { return true; } /* * @author Reker */ public String getLimitString(String query, int offset, int limit) { setSupportsVariableLimit(offset > 0); if (offset == 0) { //no offset , use top , 這時不能支援limit引數繫結 return new StringBuffer(query.length() + 8).append(query).insert(getSqlAfterSelectInsertPoint(query), " top " + limit).toString(); } return getLimitString(query, offset > 0); } /* * @author Reker */ 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 between ? and ?").toString(); }
函式類:
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; } @SuppressWarnings("unchecked") 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(); } }
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; } @SuppressWarnings("unchecked") 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(); } }
public class BitXorFunction implements SQLFunction {
public Type getReturnType(Type type, Mapping mapping) {
return Hibernate.INTEGER;
}
public boolean hasArguments() {
return true;
}
public boolean hasParenthesesIfNoArguments() {
return true;
}
@SuppressWarnings("unchecked")
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();
}
}