Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 66 ยท Data Access

Testing the Data Layer

Test repositories and queries in Spring Boot with @DataJpaTest, rollback, flush, fixtures and Testcontainers, and learn when an in-memory database misleads you.

Repository code looks too simple to break: an interface, a few method names, maybe one @Query. Yet this is where many real bugs live. A derived query that matches the wrong rows, a unique constraint you forgot to declare, a mapping that loads fine in one test and fails in production, a migration that no longer matches the entities. None of those show up in a plain unit test with a mocked repository, because the mock never talks to a database.

Spring Boot gives you two tools. A test slice, @DataJpaTest, starts only the persistence part of your application, so a data test takes a second or two instead of booting everything. Testcontainers runs the same kind of database you use in production inside a throwaway Docker container, so SQL dialect differences cannot hide. This lesson shows both, and explains the traps: rollback, the flush surprise, and test data.

Real Spring tests, JPA and Docker cannot run on this site, so the Spring code is read-only. The runnable stand-ins use real H2 through plain JDBC to show the mechanics the slice relies on: a transaction rolled back after each test, and a write buffer that only reaches the database when flushed. If you have not met the testing basics yet, look at Testing Spring Boot Applications.

Test only what you need

Slice @DataJpaTest loads entities and repositories only.
No web, no services Controllers and services are not created.
Fast Seconds, not a full application start.
1 / 2

A first data test

The test dependencies come from spring-boot-starter-test, and a spring-boot-starter-data-jpa project. Given an entity and a repository:

Java
@Entity
public class Book {
    @Id @GeneratedValue
    private Long id;
    private String title;
    private String author;
    @Column(unique = true)
    private String isbn;
    // constructors, getters
}

public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthorIgnoreCaseOrderByTitle(String author);
    boolean existsByIsbn(String isbn);
}

a test class looks like this:

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;

@DataJpaTest
class BookRepositoryTest {

    @Autowired TestEntityManager entityManager;
    @Autowired BookRepository books;

    @Test
    void findsBooksByAuthorIgnoringCase() {
        entityManager.persist(new Book("Dune", "Frank Herbert", "111"));
        entityManager.persist(new Book("Emma", "Jane Austen", "222"));
        entityManager.persist(new Book("Children of Dune", "Frank Herbert", "333"));

        var found = books.findByAuthorIgnoreCaseOrderByTitle("frank herbert");

        assertThat(found).extracting(Book::getTitle)
                .containsExactly("Children of Dune", "Dune");
    }
}

The package of the test annotations moved in Spring Boot 4, which split Boot into smaller modules. The names (@DataJpaTest, TestEntityManager) are the same; let your IDE import the right package for your version.

What the slice does for you

  • It scans @Entity classes and Spring Data repositories, and nothing else. A @Service or @RestController is not created, so if your repository test needs one, add it with @Import(MyService.class).
  • It replaces your DataSource with an embedded database (H2, HSQLDB or Derby, whichever is on the test classpath).
  • It wraps every test in a transaction and rolls it back at the end, so tests do not see each other's data.
  • It provides TestEntityManager, a small helper for arranging data directly, without using the repository you are testing.

Arranging data with TestEntityManager instead of books.save(...) has a real benefit. If save has a bug, a test that uses save to set up and findBy... to check might pass by accident. Persisting through the entity manager keeps the thing under test separate from the set-up.

Rollback: isolation without cleanup code

Because each test runs inside a transaction that is never committed, there is no @AfterEach that deletes rows. The next test starts with whatever the schema and any shared fixtures provide. The first stand-in shows the idea with a hand-made runner on H2: every test body runs, then the connection rolls back. Then it runs the same tests without rollback so you can see the damage.

Java Rollback after every test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the rollback idea, and H2 as the database. What is the stand-in: Spring's TransactionalTestExecutionListener does this around every test method; here we do it by hand. In your own tests you can change the behavior with @Commit (keep the data) or by writing @Transactional(propagation = NOT_SUPPORTED) when you need a real commit, for example to test code that uses REQUIRES_NEW.

The flush surprise

Here is the trap that surprises almost everybody once. JPA does not run insert the moment you call persist. It records the change in the persistence context and sends SQL later, on flush: before a query that might be affected, or at commit. A @DataJpaTest rolls back, so there is never a commit, and a test that only calls persist may never send the SQL at all.

Leave out the flush in a constraint test and it checks nothing: the duplicate row is never sent, so the expected error never happens. The correct version flushes inside the assertion:

Java
@Test
void rejectsDuplicateIsbn() {
    entityManager.persist(new Book("Dune", "Frank Herbert", "111"));
    entityManager.persist(new Book("Dune Messiah", "Frank Herbert", "111"));

    // Nothing has reached the database yet; the flush sends both inserts.
    assertThatThrownBy(() -> entityManager.flush())
            .isInstanceOf(PersistenceException.class);
}

Write the flush explicitly, as above, whenever the point of the test is a database rule: a unique or not-null constraint, a foreign key, a column length. Call entityManager.clear() after arranging data if you want a later query to really hit the database instead of returning the cached entity; otherwise a "lazy loading" or "mapping" bug can hide behind the first-level cache. TestEntityManager.persistAndFlush(...) combines the first two steps.

The second stand-in is a tiny write buffer over H2, so you can see why the first version of a constraint test never fails.

Java Why a constraint test needs flush

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the unique constraint and the error come from the real H2 engine, and the delay between persist and SQL is how Hibernate behaves. What is the stand-in: Hibernate also decides when to flush on its own (before queries, with FlushModeType.AUTO), tracks dirty entities and cascades; this class only queues inserts.

Fixtures and test data

You have several ways to get rows into a test. Pick the lightest one that keeps the test readable:

  • Arrange in the test. Persist the two or three rows that matter, right in the method. The reader sees cause and effect together. This is the default choice.
  • Builders or factory methods. A aBook().withAuthor("Frank Herbert").build() helper hides irrelevant fields (every Book needs an ISBN, but most tests do not care which). It keeps tests short when entities have many required columns.
  • @Sql. @Sql("/fixtures/library.sql") runs a script before the test. Good for a larger shared data set, such as a report query that needs fifty rows; the script runs in the test's transaction, so it is rolled back too.
  • Shared data from migrations. Reference data (countries, roles) that your Flyway scripts insert is already present in every test. Do not rely on rows that a test or a later script might change.

Avoid one giant shared data.sql for every test. Tests then depend on rows nobody remembers adding, and changing one value breaks a dozen tests.

Testcontainers: the real database

An embedded database is quick, but it is not PostgreSQL. It differs in SQL functions, JSON types, case sensitivity, locking, ON CONFLICT, collations and error messages. If you use native queries, database-specific types or Flyway migrations written for your engine, a test against H2 proves little. Testcontainers starts the real image for the duration of the tests.

Java
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class BookRepositoryPostgresTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired BookRepository books;

    @Test
    void usesTheRealEngine() { /* ... */ }
}

Three pieces make this work. replace = NONE tells the slice to keep the data source instead of swapping in H2. @Container starts the container before the tests and stops it after. @ServiceConnection (Boot 3.1 and later) reads the running container's host, port and credentials and configures the DataSource for you, so you no longer set spring.datasource.url by hand. With Flyway on the classpath, the migrations then run against the real engine on startup, which gives you a free check that your scripts build a working schema.

The costs are real: Docker must be available on the developer machine and in CI, and starting a database takes a few seconds. A static container shared by all tests of a class (as above) is the usual compromise. Integration tests that boot the whole application with containers are covered in a later lesson; this one stays at the repository level.

A sensible strategy

  1. Keep most repository tests on the slice with the embedded database for simple derived queries.
  2. Use the real engine through Testcontainers for native queries, migrations and anything that mentions database-specific features.
  3. Always flush (and clear) when the assertion is about SQL, constraints or mapping.
  4. Do not test Spring Data itself. findById works. Test the queries you wrote.
  5. Keep service logic out of repository tests; mock the repository in a plain unit test for that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @DataJpaTest start by default?

    It is a slice: it configures just the persistence part, replaces the data source with an embedded one and rolls each test back.
  2. 2. Why can a constraint-violation test pass or fail for the wrong reason without flush()?

    JPA delays the insert until flush or commit. Flush explicitly when the test is about what the database accepts.
  3. 3. Which setting keeps @DataJpaTest from swapping your Testcontainers database for H2?

    The slice replaces the DataSource unless told otherwise. @ServiceConnection supplies the connection details but does not stop the replacement.
  4. 4. What does @ServiceConnection on a container field do?

    Boot reads the container's host, port and credentials and creates the connection details for the data source.
  5. 5. When is an H2-only data test risky?

    H2 is not your production engine. Dialect-specific behavior is only proven by the real engine.

Summary

  • @DataJpaTest loads a persistence-only slice, uses an embedded database by default and rolls back each test.
  • Arrange data with TestEntityManager, builders or @Sql, and keep the data in the test where possible.
  • JPA delays SQL until flush; call flush() (and clear()) when testing constraints, mappings or queries.
  • Testcontainers with @ServiceConnection runs the real engine; add replace = NONE so the slice keeps it.
  • Test the queries you wrote, not Spring Data itself, and choose the database by risk.

Next: Caching.