Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 77

Testing JPA Repositories with H2 and `@DataJpaTest`

This lesson is built with resources from youtube.com, reflectoring.io and 1 more site.

Hello! Welcome back to the course.

In the last lesson, we focused on the web layer, learning how to use @WebMvcTest to test our PostController in isolation. We saw how this "test slice" approach allows us to verify HTTP mappings, request/response serialization, and controller logic without involving the full application stack, much like using supertest to test Express routes without a real database.

Today, we're moving down the stack to the persistence layer. Our goal is to write an integration test for a repository layer using @DataJpaTest with an in-memory H2 database. This is a crucial step to ensure that our data access logic—especially custom queries and entity relationships—works correctly.

Why Test the Repository Layer?

You might wonder why we need to test repositories when Spring Data JPA provides so much functionality out of the box. While we don't need to test the framework's built-in methods like save() or findById(), we absolutely must test our own additions:

  • Custom JPQL or Native Queries: These are strings, and the compiler can't verify their correctness. A test is the only way to prove they work.
  • Complex Derived Queries: A method name like findByAuthor_NameAndPublicationDateAfterOrderByTitle is complex and prone to errors. A test verifies it translates to the correct SQL.
  • Entity Mappings and Relationships: Tests can confirm that your @OneToMany, @ManyToOne, and other JPA annotations are configured correctly.

Testing this layer ensures that the contract between your application and the database schema is solid.

Spring Boot Test Types Comparison
This table helps visualize where `@DataJpaTest` fits. It's a focused integration test for the repository/DB layer, loading a partial Spring Context and running faster than a full integration test.

The Tool for the Job: @DataJpaTest

To test the persistence layer, Spring Boot provides the @DataJpaTest annotation. It's another "test slice" annotation, similar to @WebMvcTest, but tailored for JPA components.

To get a concise overview of what @DataJpaTest does and how it sets up the test environment, let's start with a short video.

Spring Boot Testing Mini-Series Part #3: Database Tests

The video "Spring Boot Testing Mini-Series Part #3" from Code With Arho provides an excellent introduction to @DataJpaTest.

Watch from 00:49 to 02:11. This segment explains why we need integration tests for the database layer and introduces how @DataJpaTest configures the necessary components and an in-memory database.

As the video explains, @DataJpaTest does several key things for us automatically:

  1. Loads a JPA-focused context: It scans for your @Entity classes and Spring Data JPA repositories (@Repository), but ignores other components like @Service or @Controller.
  2. Configures an in-memory database: It looks for a database like H2 on your classpath and configures the DataSource to connect to it, ignoring your application.yml's PostgreSQL settings. This makes tests fast and self-contained.
  3. Makes tests transactional: By default, each test method is wrapped in a transaction that is rolled back at the end. This ensures that each test starts with a clean database, providing perfect test isolation without any manual cleanup code.

MERN-to-Spring Mapping: In-Memory Databases

In the Node.js world, you might use a library like mongodb-memory-server to spin up a temporary MongoDB instance for your tests. @DataJpaTest with H2 serves the exact same purpose: providing a fast, ephemeral database to test your data access logic in isolation from your production database environment.


Hands-On: Writing a Repository Test

Let's write an integration test for our UserRepository. We'll assume you have a simple User entity and a corresponding UserRepository.

1. Add the H2 Dependency

First, ensure you have the H2 database dependency in your pom.xml. It should have the test scope, meaning it's only available for testing and won't be included in your production build.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

2. Create the Test Class

Now, let's create UserRepositoryTest.java in src/test/java.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import static org.assertj.core.api.Assertions.assertThat;

// 1. Annotate with @DataJpaTest to enable the JPA test slice
@DataJpaTest
class UserRepositoryTest {

    // 2. Autowire the TestEntityManager, a utility for test data setup
    @Autowired
    private TestEntityManager entityManager;

    // 3. Autowire the repository we want to test
    @Autowired
    private UserRepository userRepository;

    @Test
    void whenFindByEmail_thenReturnUser() {
        // --- Arrange ---
        // Create and save a user entity using TestEntityManager
        User user = new User("testuser", "test@example.com", "password123");
        entityManager.persistAndFlush(user); // persist saves to context, flush syncs to DB

        // --- Act ---
        // Use the repository method we want to test
        User found = userRepository.findByEmail(user.getEmail()).orElse(null);

        // --- Assert ---
        // Verify the result
        assertThat(found).isNotNull();
        assertThat(found.getEmail()).isEqualTo(user.getEmail());
    }
}

Let's break this down:

  • @DataJpaTest: As discussed, this sets up the entire JPA testing environment.
  • TestEntityManager: This is a helper class provided specifically for tests. It allows you to manage your entities within the persistence context. Using persistAndFlush() is often important because it forces the changes to be written to the database immediately, which is necessary if you want to test database-generated values (like IDs) or constraints.
  • userRepository: This is an instance of our actual repository interface, created and configured by Spring to work with the in-memory H2 database.

The following video provides a very clear, step-by-step demonstration of writing tests for all standard CRUD operations.

CRUD JUnit Tests for Spring Data JPA | Testing Repository Layer | Spring Boot | @DataJpaTest

The video "CRUD JUnit Tests for Spring Data JPA" from Java Guides is a practical walkthrough of setting up a repository test class and testing each operation.

Watch from 12:20 to 20:30. This covers creating the test class, autowiring the repository, and writing tests for the 'save' and 'find by ID' operations. Pay attention to the structure (Arrange, Act, Assert) and the use of assertions.


Your Task: Test a Custom Query

Now it's your turn. Imagine you have a custom query in your PostRepository to find all posts by a specific user's ID.

PostRepository.java

public interface PostRepository extends JpaRepository<Post, Long> {
    
    @Query("SELECT p FROM Post p WHERE p.author.id = :authorId")
    List<Post> findByAuthorId(@Param("authorId") Long authorId);
}

Your task is to write a test method in a new PostRepositoryTest.java class to verify that this findByAuthorId query works correctly.

Instructions:

  1. Create a PostRepositoryTest class and annotate it with @DataJpaTest.
  2. Autowire TestEntityManager and PostRepository.
  3. Write a test method findByAuthorId_whenPostsExistForAuthor_shouldReturnPosts.
  4. Arrange:
    • Create and persist a User entity (the author).
    • Create and persist two Post entities associated with that author.
    • Create and persist another User and Post to ensure your query doesn't just return all posts.
  5. Act:
    • Call postRepository.findByAuthorId() with the ID of the first author.
  6. Assert:
    • Assert that the returned list is not null and has a size of 2.
    • Assert that the titles of the posts in the list match the ones you created.

If you get stuck, the article "Testing JPA Queries with Spring Boot and @DataJpaTest" provides excellent examples of how to populate data and structure your tests.

Testing JPA Queries with Spring Boot and @DataJpaTest

This article from reflectoring.io is a great written reference for everything we've discussed. It covers what to test, schema creation, and different ways to populate the database.

Refer to the section "Populating the Database", particularly the subsection "Inserting Entities Manually". It reinforces the pattern of using the repository or TestEntityManager to set up your test data directly in Java, which is the approach you're taking.

Click here for the solution
// In src/test/java/.../posts/PostRepositoryTest.java

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class PostRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private PostRepository postRepository;

    @Test
    void findByAuthorId_whenPostsExistForAuthor_shouldReturnPosts() {
        // --- Arrange ---
        // Author 1 and their posts
        User author1 = new User("author1", "author1@example.com", "pass");
        entityManager.persist(author1);

        Post post1 = new Post("Title 1", "Content 1", author1);
        Post post2 = new Post("Title 2", "Content 2", author1);
        entityManager.persist(post1);
        entityManager.persist(post2);

        // Author 2 and their post (to ensure our query is selective)
        User author2 = new User("author2", "author2@example.com", "pass");
        entityManager.persist(author2);
        Post post3 = new Post("Title 3", "Content 3", author2);
        entityManager.persist(post3);
        
        entityManager.flush(); // Sync all changes to the H2 database

        // --- Act ---
        List<Post> foundPosts = postRepository.findByAuthorId(author1.getId());

        // --- Assert ---
        assertThat(foundPosts).hasSize(2);
        assertThat(foundPosts).extracting(Post::getTitle).containsExactlyInAnyOrder("Title 1", "Title 2");
    }
}

Debugging & Trade-offs: In-Memory vs. Real Databases

The @DataJpaTest approach with H2 is fast and convenient, but it has a major limitation: the in-memory database might behave differently from your production database (PostgreSQL). This is especially true if you use native SQL queries with dialect-specific functions. A test could pass on H2 but fail in production.

The ultimate solution, which we will implement later in the course, is to use Testcontainers. This library lets you programmatically start a real PostgreSQL Docker container for your tests. @DataJpaTest can be configured to connect to this container instead of H2, giving you the best of both worlds: isolated, automated tests running against the exact same database technology as production.

The "Code With Arho" video touches on this powerful concept.

Spring Boot Testing Mini-Series Part #3: Database Tests

Let's revisit the "Code With Arho" video to understand the solution to the in-memory database problem.

Watch from 04:43 to 06:51. You don't need to implement this now, but focus on the why. The video explains the problems with using different database engines and introduces Testcontainers as the way to run tests against a real database in a Docker container.


Conclusion

You've successfully added another critical testing technique to your toolkit. You can now write focused integration tests for your data persistence layer, verifying that your entities, repositories, and custom queries all work together as expected.

Key Takeaways:

  • @DataJpaTest is the primary annotation for testing the JPA layer in isolation.
  • It automatically configures a JPA-focused Spring context and connects to an in-memory H2 database by default.
  • Tests are transactional and rolled back automatically, ensuring each test is independent.
  • TestEntityManager is a convenient utility for setting up database state within your test methods.
  • While H2 is fast, Testcontainers with a real database (like PostgreSQL) is the most reliable approach for ensuring query correctness, which we'll adopt later.

Preview of the Next Lesson:
We've tested our controller slice (@WebMvcTest) and our data slice (@DataJpaTest). The next logical step is to test the whole application stack. In the upcoming lesson, we will write a full application integration test using @SpringBootTest and Testcontainers. This will involve loading the entire Spring context and verifying a complete API flow from an HTTP request all the way to a real PostgreSQL database.