Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

In this tutorial, we'll learn about the findFirst() and findTop() methods from Spring Data JPA. These methods provide data retrieval functionality. They map to the corresponding select queries in SQL.

2. Spring Data JPA API

Spring Data JPA is one of the frameworks under the Spring project. It provides the API to work with the persistence layer, i.e., we use it for the data access layer for our RDBMS.

The JpaRepository interface provides one way of implementing the data access layer.

JpaRepository is a generic interface. We define an interface that extends JpaRepository. The interface is typed with our Entity and the Entity‘s primary key. Next, we add method declarations to our repository interface.

The Spring framework then generates the interface implementation. The interface methods' code is automatically generated. As a result, we get the data access layer over our persistence store.

The Spring framework loads our Repository bean in the container. Using the @Autowired annotation, we can inject this Repository bean in our components. This takes away the complexity of writing SQL queries. We get typed data that enhances debugging capabilities. Spring Data JPA is a great productivity booster.

3. Using Spring Data JPA findFirst()

Data retrieval is the core operation of a data access layer. findFirst(), as its name suggests, is a data retrieval method. The “First” in the name indicates that it retrieves data from the start of a set of records. Mostly we need a subset of data records based on some criteria.

Let's take an example of an entity Student holding student data. Its fields are studentId, name, and score:

class Student{
    private Long studentId;
    private String name;
    private Double score;

Next, we define the corresponding Repository, named StudentReposity. This is an interface that extends from JpaRepository. We passed the types Student and Long to the JpaRepository. This creates a data access layer for our Student entity:

public interface StudentRepository extends JpaRepository<Student, Long> {

    Student findFirstByOrderByScoreDesc();
    List<Student> findFirst3ByOrderByScoreDesc();

3.1. Method Name Significance

The method name findFirstByOrderByScoreDesc() is not random. Each part of the method name findFirstByOrderByScoreDesc() has its significance.

“find” means it maps to a select query. “First” means it retrieves the first record from the list of records. “OrderByScore” signifies that we want the records to be sorted by the score property. “Desc” means that we want the sorting to be in reverse order. The return type of this method is a Student object.

The Spring framework intelligently evaluates the method name. It then generates and executes the query to build our desired output. In our particular case, it retrieves the first Student record. It first sorts the Student records in descending order by score. Hence, we get the top scorer among all the Students.

3.2. Returning Collection of Records

The next method is findFirst3ByOrderByScoreDesc(). There are some new features present in the declaration of this method.

First, the return type is a collection of Students rather than a singular Student object. Second, we have the number 3 after “findFirst”. This means we're expecting multiple records as output from this method.

The 3 in the method name defines the exact count of records we expect. If the total records are less than 3, then we get less than 3 records in the result.

This method also sort by the score property in reverse order. Next, it takes the first 3 records and returns them as a list of records. Hence, we get the top three Students by score. We can change the limiting number to 2, 4, etc.

3.3. Mixing Up With Filter Criteria

We can define the same limiting methods in different ways while mixing up with other filter criteria too:

public interface StudentRepository extends JpaRepository<Student, Long>{

  Student findFirstBy(Sort sort);
  Student findFirstByNameLike(String name, Sort sort);

  List<Student> findFirst2ByScoreBetween(int startScore, int endScore, Sort sort);

Here, findFirstBy() defines Sort as a parameter. This makes findFirstBy() a generic method. We'll define the sort logic before making the method call.

findFirstByNameLike() creates a filter on the Student name in addition to the findFirstBy() functionality.

findFirst2ByScoreBetween() defines the range of scores. It sorts the Students by the Sort criteria. Then it finds the first two Students between the start and end score range.

Let's see how we create a Sort object:

Sort sort ="score").descending();

The by() method takes the property name as a string on which we want to sort. On the other hand, the descending() method call makes the sort in reverse order.

4. Using Spring Data JPA findTop()

Next comes the findTop() method. findTop() is just another name for the same findFirst() method. We can use firstFirst() or findTop() interchangeably without any issue.

They are just aliases and a matter of liking by developers without any practical impact. Here's the findTop() flavor of the same methods we saw earlier:

public interface StudentRepository extends JpaRepository<Student, Long> {

    Student findTopByOrderByScoreDesc();
    List<Student> findTop3ByOrderByScoreDesc();
    Student findTopBy(Sort sort);
    Student findTopByNameLike(String name, Sort sort);
    List<Student> findTop2ByScoreBetween(int startScore, int endScore, Sort sort);

5. Conclusion

In this article, we have learned about the two methods, findFirst() and findTop(), provided by the Spring Data JPA API. The two methods can be used as the foundation for more complex retrieval methods.

We have seen a few examples of mixing findFirst() and findTop() with other filter criteria. A single record is returned when findFirst() or findTop() is used without a number. If findFirst() or findTop() is appended by a number, then the records are retrieved up to that number.

An important learning point is that we can use either findFirst() or findTop(). It's a matter of personal choice. There are no differences between findFirst() and findTop().

As always, the source code for the examples is available over on GitHub.

Persistence bottom

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Persistence footer banner
Inline Feedbacks
View all comments