eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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:

@Entity
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:

@Repository
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:

@Repository
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 = Sort.by("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.

When findFirst() method is called, the following query is executed under the hood, so it limits the result (limit 1):

select student0_."id" as id1_0_, student0_."name" as name2_0_, student0_."score" as score3_0_ from "student" student0_ order by student0_."score" desc limit ?

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:

@Repository
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);
}

When a method with findTop is called, the following query is executed under the hood, so it limits the result (limit 1):

select student0_."id" as id1_0_, student0_."name" as name2_0_, student0_."score" as score3_0_ from "student" student0_ order by student0_."score" desc limit ?

As you see, the executed query of findFirst() is the same as findTop().

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().

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments