Select top 1 result using JPA

Viewed 156232

I need to bring from DB only one single result. How can I do that with JPA?

Select top 1 * from table

I tried

"select t from table t"

query.setMaxResults(1);

query.getSingleResult();

but didn't work. Any other ideas?

5 Answers

2021 att: you can use TOP or FIRST in Spring Data JPA

example:

User findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);

doc: https://docs.spring.io/spring-data/jpa/docs/2.5.4/reference/html/#repositories.limit-query-result

Related