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.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJU – NPI (tag = JUnit)
announcement - icon

Master the most popular testing framework for Java, through the Learn JUnit course:

>> LEARN JUNIT

1. Introduction

When working with Spring Boot applications that utilize Spring Data JPA for data persistence, it’s crucial to test the repositories that interact with the database. In this tutorial, we’ll explore how to effectively test Spring Data JPA repositories using the @DataJpaTest annotation provided by Spring Boot along with JUnit.

2. Understanding @DataJpaTest and Repository Class

In this section, we’ll delve into the interaction between @DataJpaTest and class repositories within the context of Spring Boot applications.

2.1. @DataJpaTest

The @DataJpaTest annotation is used to test JPA repositories in Spring Boot applications. It’s a specialized test annotation that provides a minimal Spring context for testing the persistence layer. This annotation can be used in conjunction with other testing annotations like @RunWith and @SpringBootTest.

In addition, the scope of @DataJpaTest is limited to the JPA repository layer of the application. It doesn’t load the entire application context, which can make testing faster and more focused. This annotation also provides a pre-configured EntityManager and TestEntityManager for testing JPA entities.

2.2. Repository Class

In Spring Data JPA, repositories serve as an abstraction layer on top of JPA entities. It provides a set of methods for performing CRUD (Create, Read, Update, Delete) operations and executing custom queries. These repositories typically extend from interfaces like JpaRepository and are responsible for handling database interactions related to specific entity types.

3. Optional Parameters

@DataJpaTest does have some optional parameters we can use to customize the test environment.

3.1. properties

This parameter allows us to specify Spring Boot configuration properties that will be applied to our test context. This can be useful for adjusting settings like database connection details, transaction behavior, or other application properties relevant to our testing needs:

@DataJpaTest(properties = {
    "spring.datasource.url=jdbc:h2:mem:testdb",
    "spring.jpa.hibernate.ddl-auto=create-drop"
})
public class UserRepositoryTest {
    // ... test methods
}

3.2. showSql

This enables SQL logging for our tests and allows us to see the actual SQL queries executed by the repository methods. Moreover, this can help debug or understand how the JPA queries are translated. By default, the SQL logging is enabled. We can turn it off by setting the value to false:

@DataJpaTest(showSql = false)
public class UserRepositoryTest {
    // ... test methods
}

3.3. includeFilters and excludeFilters

These parameters enable us to include or exclude specific components during component scanning. We can use them to narrow down the scanning scope and optimize test performance by focusing only on the relevant components:

@DataJpaTest(includeFilters = @ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE, 
    classes = UserRepository.class),
  excludeFilters = @ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE, 
    classes = SomeIrrelevantRepository.class))
public class UserRepositoryTest {
    // ... test methods
}

4. Key Features

When it comes to testing JPA repositories in Spring Boot applications, the @DataJpaTest annotation can be a handy tool. Let’s explore its key features and benefits in detail.

4.1. Test Environment Configuration

Setting up a proper test environment for JPA repositories can be time-consuming and tricky. @DataJpaTest provides a ready-made testing environment that includes essential components for testing JPA repositories, such as the EntityManager and DataSource.

This environment is specifically designed for testing JPA repositories. It ensures that our repository methods run within the context of a test transaction, interacting with a safe, in-memory database like H2 instead of the production database.

4.2. Dependency Injection

@DataJpaTest simplifies the process of dependency injection within our test classes. Repositories, along with other essential beans, are automatically injected into the test context. This seamless integration enables developers to focus on writing concise and effective test cases without the hassle of explicit bean wiring.

4.3. Rollback by Default

Moreover, keeping tests independent and reliable is crucial. By default, each test method annotated with @DataJpaTest runs within a transactional boundary. This ensures that changes made to the database are automatically rolled back at the end of the test, leaving a clean slate for the next test.

5. Configuration and Setup

To use @DataJpaTest, we need to add the spring-boot-starter-test dependency to our project with scope “test“. This lightweight dependency includes essential testing libraries like JUnit for testing, ensuring it’s not included in our production build.

5.1. Adding Dependency to pom.xml

Let’s add the following dependency to the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Once we’ve added the dependency, we can use the @DataJpaTest annotation in our tests. This annotation sets up an in-memory H2 database and configure Spring Data JPA for us, allowing us to write tests that interact with our repository classes.

5.2. Creating the Entity Class

Now, let’s create the User entity class, which will represent user data:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    
    // getters and setters
}

5.3. Creating the Repository Interface

Next, we define the UserRepository, a Spring Data JPA repository interface for managing User entities:

public interface UserRepository extends JpaRepository<User, Long> {
    // Add custom methods if needed
}

By extending JpaRepository<User, Long>, our UserRepository gains access to standard CRUD operations provided by Spring Data JPA out-of-the-box.

Additionally, we can define custom query methods within this interface to suit specific data access retrieval needs, such as findByUsername():

public interface UserRepository extends JpaRepository<User, Long> {
    // Custom query method to find a user by username
    User findByUsername(String username);
}

6. Implementing Repository Tests

To test the repository layer of our application, we’ll utilize the @DataJpaTest annotation. By using this annotation, an in-memory H2 database will be set up, and Spring Data JPA will be configured. This allows us to write tests that interact with our repository classes.

6.1. Setting up the Test Class

To begin, let’s set up the test class by annotating it with @DataJpaTest. This annotation scans for entity classes annotated with @Entity and Spring Data JPA repositories interfaces. This ensures that only relevant components are loaded for testing, improving test focus and performance:

@DataJpaTest
public class UserRepositoryTest {
    // Add test methods here
}

To create a repository test case, we first need to inject the repository that we want to test into our test class. This can be done using the @Autowired annotation:

@Autowired
private UserRepository userRepository;

6.2. Test Lifecycle Management

In the context of test lifecycle management, @BeforeEach and @AfterEach annotations are used to perform setup and teardown operations before and after each test method, respectively. This ensures that each test method runs in a clean and isolated environment, with consistent initial conditions and cleanup procedures.

Here’s how we can incorporate test lifecycle management into our test class:

private User testUser;

@BeforeEach
public void setUp() {
    // Initialize test data before each test method
    testUser = new User();
    testUser.setUsername("testuser");
    testUser.setPassword("password");
    userRepository.save(testUser);
}

@AfterEach
public void tearDown() {
    // Release test data after each test method
    userRepository.delete(testUser);
}

In the setUp() method annotated with @BeforeEach, we can perform any necessary setup operations required before each test method execution. This might include initializing test data, setting up mock objects, or preparing resources needed for the test.

Conversely, in the tearDown() method annotated with @AfterEach, we can perform cleanup operations after each test method execution. This might involve resetting any changes made during the test, releasing resources, or performing any necessary cleanup tasks to restore the test environment to its original state.

6.3. Testing the Insertion Operation

Now, we can write test methods that interact with the JPA repository. For example, we might want to test that we can save a new user to the database. Since a user is automatically saved before each test, we can directly focus on testing interactions with the JPA repository:

@Test
void givenUser_whenSaved_thenCanBeFoundById() {
    User savedUser = userRepository.findById(testUser.getId()).orElse(null);
    assertNotNull(savedUser);
    assertEquals(testUser.getUsername(), savedUser.getUsername());
    assertEquals(testUser.getPassword(), savedUser.getPassword());
}

If we observe the console log for the test case, we’ll notice the following logs:

Began transaction (1) for test context  
.....

Rolled back transaction for test:  

These logs indicate that the @BeforeEach and @AfterEach methods are functioning as expected.

6.4. Testing the Update Operation

In addition, we can create a test case for testing the update operation:

@Test
void givenUser_whenUpdated_thenCanBeFoundByIdWithUpdatedData() {
    testUser.setUsername("updatedUsername");
    userRepository.save(testUser);

    User updatedUser = userRepository.findById(testUser.getId()).orElse(null);

    assertNotNull(updatedUser);
    assertEquals("updatedUsername", updatedUser.getUsername());
}

6.5. Testing the findByUsername() Method

Now, let’s test the findByUsername() custom query method we created:

@Test
void givenUser_whenFindByUsernameCalled_thenUserIsFound() {
    User foundUser = userRepository.findByUsername("testuser");

    assertNotNull(foundUser);
    assertEquals("testuser", foundUser.getUsername());
}

7. Transactional Behavior

By default, all tests annotated with @DataJpaTest are executed within a transaction. This means that any changes made to the database during the test are rolled back at the end of the test, ensuring that the database is left in its original state. This default behavior simplifies testing by preventing interference between tests and data corruption.

However, there may be cases where we need to disable transactional behavior to test certain scenarios. For instance, testing results may need to persist beyond the test.

In such a case, we can disable transactions for a specific test class using the @Transactional annotation with propagation = propagation.NOT_SUPPORTED:

@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class UserRepositoryIntegrationTest {
    // ... test methods
}

Or we can disable transactions for an individual test method:

@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testMyMethodWithoutTransactions() {
    // ... code that modifies the database
}

8. Conclusion

In this article, we learned how to use @DataJpaTest to test our JPA repository in JUnit. Overall, @DataJpaTest is a powerful annotation for testing JPA repositories in Spring Boot applications. It provides a focused testing environment and pre-configured tools for testing persistence layers. By using @DataJpaTest, we can ensure that our JPA repositories are functioning correctly without having to start up the entire Spring context.

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