Spring JPA Java data - get the last 10 records from a query

Is there a way to get the latest number of X results from a query?

For example, if you want to get the first ten results, I see that this example works: setMaxResults for Spring -Data-JPA annotations?

 public interface UserRepository extends Repository<User, Long> {

       List<User> findByUsername(String username, Pageable pageable);
 }
 //and then I could call it like this
 Pageable topTen = new PageRequest(0, 10);
 List<User> result = repository.findByUsername("Matthews", topTen);

But how do I get the last 10 entries?

The only way I could do this is to flip the order in the query (findByUsernameDesc, assuming the original results were upstream) and then iterate over the list back so that I can process it in the order I wanted (ascending) ,

It seems like an ugly way to do it. Is there a way for the query to give me the latest X results in the order I want?

+4
5

, , .

, maxResult, .

. 100M X, .

+2

Spring JPA 1.7 "" "" , :

public interface UserRepository extends Repository<User, Long> {

   List<User> findFirst10ByUsername(String username);
}

- Spring Evans Go GA >

+12

PageRequest . PageRequest.

, :

Pageable topTen = new PageRequest(0, 10, Direction.ASC, "username"); 
List<User> result = repository.findByUsername("Matthews", topTen);

( ).

@Query(value="select p from Person p")
public List<Person> findWithPageable(Pageable pageable);

:

repository.findWithPageable(new PageRequest(0, 10, Direction.DESC, "id"));
+4

, 10 :

 List<User> findFirst10ByUsernameOrderByIdDesc(String username);
+1

, ( ), - , max .

spring -data-jpa, firstresult .

// this is a hibernate query... but should be simple
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult(); 

//Get the last ten
Pageable topTen = new PageRequest(count - 10, count);
List<User> result = repository.findByUsername("Matthews", topTen);
0

Source: https://habr.com/ru/post/1543467/


All Articles