Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the first row from a SELECT operation using JPQL?

I have a database with data about some tests, I want to order them decently using their attribute DATE and take only the first one of all of them. I mean, the equivalent TOP 1 of SQL in JPQL.

Thanks for your help!

like image 999
Iván Sánchez Castellanos Avatar asked Jun 12 '19 16:06

Iván Sánchez Castellanos


People also ask

Which method is used to execute a select JPQL query?

The EntityManager's createQuery is used to create the Query instance whose getResultList method is then used to execute the JPQL query passed to createQuery as the parameter.

Can we use subquery in JPQL?

Yes, It is possible to use subquery with IN operator in JPQL. I had a similar usecase and it worked for me. My query was as follows.

Which annotation is used for binding JPQL query with method?

The @Query annotation can be used to create queries by using the JPA query language and to bind these queries directly to the methods of your repository interface.

In which order the results are sorted for JPQL query?

You can define the order in which the database shall return your query results with an ORDER BY clause. Its definition in JPQL is similar to SQL. You can provide one or more entity attributes to the ORDER BY clause and specify an ascending (ASC) or a descending (DESC) order.


2 Answers

In spring jpa you can do something like this

Foo findTopByOrderByDateDesc(); //This will return 1st item

List<Foo> findTop10ByOrderByDateDesc(); //This will return top 10 item

For reference Spring Jpa Doc

like image 148
Avi Avatar answered Sep 21 '22 20:09

Avi


You normally set that on the Query object before triggering the fetch:

entityManager.createQuery("...")
       .setMaxResults(1)
       .getResultList();

With the use of Spring Data Jpa syntax you would use something like:

Optional<Test> findFirstByOrderByDateDesc();

Or using Pageable:

Page<Test> test = repository.findAll(
    PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "date")));
like image 33
Maciej Kowalski Avatar answered Sep 24 '22 20:09

Maciej Kowalski