分頁外掛將SQLServer查詢語句轉換成分頁語句
Maven地址:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.0</version>
</dependency>
測試:
import com.github.pagehelper.parser.SqlServer; public class Test{ public static final SqlServer sqlServer = new SqlServer();//初始化 @Test public void testSqlUnion() throws JSQLParserException { String originalSql = "select distinct countrycode,countryname from country order by countrycode"; System.out.println(sqlServer.convertToPageSql(originalSql, 1, 10)); } }
測試結果(已格式化):
SELECT TOP 10 PAGE_TABLE_ALIAS.countrycode, PAGE_TABLE_ALIAS.countryname FROM (SELECT DISTINCT ROW_NUMBER() OVER(ORDER BY countrycode) PAGE_ROW_NUMBER, countrycode, countryname FROM country) AS PAGE_TABLE_ALIAS WHERE PAGE_ROW_NUMBER > 1 ORDER BY PAGE_ROW_NUMBER
注意:
1.由於需要提取order by,所以儘可能保證最外層的SQL包含order by
2.如果沒有order by,那麼上面呼叫的convertToPageSql還有第四個引數orderBy
public String convertToPageSql(String sql, int offset, int limit, String orderBy)
如果原來的sql有order by,那麼通過該方法指定orderBy之後會覆蓋原sql中的order by人為指定的時候很難把握欄位名字的寫法,所以建議在sql中帶上order by