package com.walker.db.page;
|
|
import java.util.Locale;
|
|
/**
|
* 描述:分页工具,根据不同数据库生成不同sql分页语句
|
* @author 时克英
|
* @date 2020年7月23日 下午6:22:35
|
*/
|
|
public class PageUtils {
|
|
public static final String getLimitStringForMysql(String sql, boolean hasOffset){
|
return sql + (hasOffset ? " limit ?, ?" : " limit ?");
|
}
|
|
public static final String getLimitStringForOracle(String sql, boolean hasOffset){
|
sql = sql.trim();
|
String forUpdateClause = null;
|
boolean isForUpdate = false;
|
int forUpdateIndex = sql.toLowerCase(Locale.ROOT).lastIndexOf("for update");
|
if (forUpdateIndex > -1) {
|
forUpdateClause = sql.substring(forUpdateIndex);
|
sql = sql.substring(0, forUpdateIndex - 1);
|
isForUpdate = true;
|
}
|
|
StringBuilder pagingSelect = new StringBuilder(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 <= ?");
|
}
|
|
if (isForUpdate) {
|
pagingSelect.append(" ");
|
pagingSelect.append(forUpdateClause);
|
}
|
|
return pagingSelect.toString();
|
}
|
|
public static final String getLimitStringForSQLServer(String querySelect, int offset, int limit) {
|
if (offset > 0) {
|
throw new UnsupportedOperationException("query result offset is not supported");
|
} else {
|
return (new StringBuilder(querySelect.length() + 8)).append(querySelect).insert(getAfterSelectInsertPoint(querySelect), " top " + limit).toString();
|
}
|
}
|
|
static int getAfterSelectInsertPoint(String sql) {
|
int selectIndex = sql.toLowerCase(Locale.ROOT).indexOf("select");
|
int selectDistinctIndex = sql.toLowerCase(Locale.ROOT).indexOf("select distinct");
|
return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
|
}
|
}
|