Spring Certified Professional 2023 · Free Practice Question Easy

Question 32

Which ordering operator can be used in the declaration of custom finder methods in a Spring Data JPA Repository Interface? (select 2)

  • A

    Desc

  • B

    Ascending

  • C

    Asc

  • D

    Descending

Reveal correct answers

Correct answers: A, C

Explanation

Asc and desc

Here's a code example demonstrating the usage of the ordering operators "Asc" and "Desc" in a custom finder method declaration in a Spring Data JPA Repository Interface:

In the above example, the UserRepository interface extends JpaRepository and defines two custom finder methods. The method findAllByOrderByLastNameAsc() returns a list of users sorted in ascending order by their last name. The method findAllByOrderByAgeDesc() returns a list of users sorted in descending order by their age.

Note that the ordering operators "Asc" and "Desc" are appended to the property names (e.g., "LastName" and "Age") to indicate the desired sorting order.

Please ensure that you have the necessary entities (e.g., User class) and the appropriate configuration in place for Spring Data JPA to work correctly.


Springdoc:

The query builder mechanism built into the Spring Data repository infrastructure is useful for building constraining queries over entities of the repository.

The following example shows how to create a number of queries:

Example 13. Query creation from method names

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



See also: Order the results of a derived query

You can, of course, also order your query results. In JPQL, this would require an ORDER BY clause in your query. With Spring Data JPA, you just need to add the words OrderBy to your query followed by the name of the entity attribute and the abbreviations ASC or DESC for your preferred order.

The following example uses this feature to retrieve all Book entities whose title contains a provided String in the ascending order of their title.

When you call this method on the BookRepository, Spring Data JPA and Hibernate generate an SQL statement with the expected ORDER BY clause.

https://thorben-janssen.com/ultimate-guide-derived-queries-with-spring-data-jpa

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need