分页插件将SQLServer查询语句转换成分页语句

本文介绍如何使用Mybatis-PageHelper进行SQL分页处理,包括配置方法及测试示例。PageHelper适用于Mybatis环境,简化了分页操作,并提供了多种方式来实现SQL的分页查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分页插件地址:https://github.com/pagehelper/Mybatis-PageHelper

本次演示使用jar包版本:http://repo1.maven.org/maven2/com/github/pagehelper/pagehelper/4.2.0/pagehelper-4.2.0.jar

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值