56

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?

Gondim
  • 3,038
  • 8
  • 44
  • 62

6 Answers6

66

Try like this

String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();

It should work

UPDATE*

You can also try like this

query.setMaxResults(1).getResultList();
Jorge
  • 17,896
  • 19
  • 80
  • 126
22

To use getSingleResult on a TypedQuery you can use

query.setFirstResult(0);
query.setMaxResults(1);
result = query.getSingleResult();
pinguinjesse
  • 221
  • 2
  • 2
14

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

Rodrigo R
  • 311
  • 3
  • 11
8

The easiest way is by using @Query with NativeQuery option like below:

@Query(value="SELECT 1 * FROM table ORDER BY anyField DESC LIMIT 1", nativeQuery = true)
Ayman Al-Absi
  • 2,630
  • 24
  • 22
2

Use a native SQL query by specifying a @NamedNativeQuery annotation on the entity class, or by using the EntityManager.createNativeQuery method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • Can you please give me an example? I've never used that. – Gondim Jul 15 '11 at 14:06
  • @pringlesinn, take a look at the example at [java2s.com](http://www.java2s.com/Code/Java/JPA/UsingNamedNativeQuery.htm). You will need to modify the query in the `@NamedNativeQuery` annotation to the one you desire, and also change the attribute value of resultClass to the one that represents the result. – Vineet Reynolds Jul 15 '11 at 14:11
1

Use Pageable with size is 1 and sort by the field you want it should work

  @Query("from Cat t order by t.name desc")
  Page<Cat> findCats(Pageable page);

the page should be use is

Pageable page = PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "name"));
helvete
  • 2,455
  • 13
  • 33
  • 37