Spring JPA data, how to get the last page through the page

I wanted to get the last 5 entries of an entity. But you cannot get it through Spring Data JPA.

I originally tried to get data through a LIMIT request, but LIMIT is not supported in JPA.

Later I tried with the Pageable interface.

 Pageable pageCount = new PageRequest(0, 10, Direction.ASC,"id"); List<TxnEntity> txnEntities = txnDAO .findByAccountEntity(accountEntity,pageCount); 

This gives me the first page with 10 objects.

But my requirement is to get the last 10 or 5 objects. So, how can I get it through the Pageable interface within Spring?

+7
java spring hibernate jpa
source share
4 answers

The output I was expecting was the last n entries.

So, I used the Spring Data JPA 1.7 inline query

 int n = 10; Pageable pageCount = new PageRequest(0, n); List<TxnEntity> txnEntities = txnDAO .findByAccountEntityOrderByIdDesc(accountEntity,pageCount); 

Now this will return the last n records.

DAO will return all records in descending order, and using Pageable you can specify how many records we need from the bottom.

It was easy.

For additional queries requested by JPA: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/

+3
source share

From the reference documentation:

To find out how many pages you get for a request, you need to call an additional counting request. By default, this request will be obtained from the request that you call.

You can determine the number of pages by first requesting a counter:

 Long count = txnDAO.countByAccountEntity(accountEntity); Pageable pageCount = new PageRequest((int)count/10, 10, Direction.ASC,"id"); 
+3
source share

You can change your look and then get the first 5.

0
source share

For reference only:

By http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result

you can also create the findTop5ByAccountEntityOrderByIdDesc(accountEntity) method in your repository. I would prefer this from a solution with an extra count request.

If you want, you can also add the Pageable parameter, but that doesn't make much sense.

However, there are several potential problems: id is not a natural way to find the "last" entries. It will always give you the same result, but depending on the generation strategy and how identifiers are potentially cached, it is not guaranteed that the last "saved" object has the highest identifier. This may work in 90% of cases, but you have to be careful there.

Is that what you intend to do?

0
source share

All Articles