Spring Data: end result for custom query

In my Spring data repository, I (should) use custom queries using annotation @Query. I know that I can limit the number of results in a named query like

Iterable<Person> findFirst5OrderByLastName()

or that you can limit the number of results by passing a page like

Iterable<Person> findByLastName(String lastName, Pageable pageable)

But is it possible to achieve this using custom annotation @Query?

TIA

EDIT

since I see that my question is a bit confusing, some clarifications: I want to limit the number of results obtained when using a custom query so that I don’t

1) you need to specify the size of the result through the page

2) you must use a named query to indicate the size of the result

In fact, I want the limit on the number of results to be completely transparent when calling a method (therefore, not passed Pageable) and not rely on the Spring Data naming scheme (it is best to pass through a user name as the method value / function)

+4
source share
3 answers

You can try the following:

@Entity
@Table(name = "persons") 
public class Person {
    //...
}

@Query(value = "select * from persons limit 50", nativeQuery = true)
List<Person> getFirst50();

Remember to check if your SQL server supports the keyword.

0
source

You need to extend PagingAndSortingRepository

and add method

Page<Person> listAllByPage(Pageable pageable)

See an example

0
source

Of course, you can use @Query to order the result, this is a JPQL query, for example.

@Query("SELECT u FROM User u ORDER BY u.name ASC")

Further sorting can be performed either provided that you have the PageRequest parameter or use Sort directly.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.sorting

0
source

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


All Articles