简体   繁体   中英

How can I make pagination with only jdbc and standard sql?

I am starting a new project in java. I want to use only jdbc, no hibernate or jpa. My database is Microsoft SQL Server. But it seems to be very complicated to do pagination with pure jdbc and sql. There is built in support in hibernate/jpa for pagination. But I wanted go only with jdbc and standard sql. Searching over the internet I found various answers, all them try to solve the problem with modifying the original query. I wanted to avoid adding anything in my original query just for pagination.

My SQL Server version is "Microsoft SQL Server 2008"

In SQL Server 2012 and above you can use OFFSET FETCH clause, but in SQL Server 2005 and above you can use ROW_NUMBER() function. Here you have an example:

DECLARE @PageNumber int = 1;
DECLARE @PageSize int = 20;

WITH Q AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY TheOrderColumn) AS record_number
    FROM YourOriginalQuery
)
SELECT *
FROM Q
WHERE 
    record_number > (@PageNumber - 1) * @PageSize
    AND record_number <= @PageNumber * @PageSize
ORDER BY record_number;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM