Ch. 8 · Spring Boot

@DataJpaTest vs Testcontainers: Testing Spring Data Repositories

What @DataJpaTest loads, why its rollback and embedded database can hide bugs, and how to test Spring Data repositories with Testcontainers.

~6 min readintermediateupdated Nov 1, 2026

A Spring Data repository test is only useful if it proves something about the database. “@DataJpaTest with H2” is a fine starting point, but it comes with three caveats: the test runs inside a transaction that rolls back, the first-level cache can answer queries without any SQL, and H2 is not PostgreSQL. Each one can let a green test suite approve code that fails in production. The examples target Spring Boot 3.1+ (for @ServiceConnection) with Hibernate 6, and the Testcontainers ones need Docker running.

What @DataJpaTest gives you, and what to add

@DataJpaTest is a test slice: it starts only JPA-related auto-configuration (entities, repositories, DataSource, Flyway or Liquibase, TestEntityManager) and not your services or web layer. Each test runs in a transaction that rolls back afterwards. By default it replaces your DataSource with an embedded database if one is on the classpath. For realistic tests, use @AutoConfigureTestDatabase(replace = NONE) with a Testcontainers database exposed through @ServiceConnection, run the same migrations as production, and flush and clear the persistence context so assertions read from the database rather than from memory.

Rollback, the first-level cache and the swapped database

@DataJpaTest is a composed annotation. Among other things, it includes @Transactional, @AutoConfigureTestDatabase and a type-exclusion filter that skips @Service, @Controller and @Component beans.

@DataJpaTest
class CustomerRepositoryTest {

    @Autowired CustomerRepository customers;
    @Autowired TestEntityManager em;

    @Test
    void findsByEmailIgnoringCase() {
        em.persist(new Customer("Ada", "ADA@example.com"));
        em.flush();
        em.clear();

        assertThat(customers.findByEmailIgnoreCase("ada@example.com")).isPresent();
    }
}
java

Three behaviours matter:

  1. Rollback. Data written in one test disappears before the next, which keeps tests independent. It also means the commit never happens, so anything that only runs at commit, such as deferred constraint checks or @TransactionalEventListener(phase = AFTER_COMMIT), never runs.
  2. First-level cache. Within one transaction, findById for an entity you just persisted returns the same Java object from the persistence context without SQL. Without flush() the INSERT may never be sent, so constraint violations go unseen.
  3. Database replacement. With H2 on the test classpath, Boot swaps your configured database for it. Your PostgreSQL-specific SQL, column types and constraint behaviour are no longer tested.

From an H2 slice to the real engine and real migrations

Step 1: Start with the slice

The slice starts in a second or two because it skips the web server, security and your services. Use it for repository queries, entity mappings and constraints. Anything else the repository needs, such as an auditing configuration, must be imported explicitly with @Import.

Step 2: Run against the real database engine

Add spring-boot-testcontainers and the Testcontainers PostgreSQL module, then:

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

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

    @Autowired CustomerRepository customers;
    @Autowired TestEntityManager em;
}
java

@ServiceConnection makes Boot create the connection details from the container, so no spring.datasource.url property is needed. replace = NONE stops Boot from swapping in an embedded database. Spring Boot 3.4 and later leave a @ServiceConnection database in place by default, but the explicit setting keeps the test working on older versions and makes the intent visible. The static container starts once per class.

Step 3: Use production migrations

Let Flyway or Liquibase build the schema, and set spring.jpa.hibernate.ddl-auto=validate (Boot’s default for an embedded database with no Flyway or Liquibase is create-drop). Then the tests verify that your entities match the schema your migrations produce, which is the schema production has.

# src/test/resources/application.properties
spring.jpa.hibernate.ddl-auto=validate
properties

Step 4: Flush, clear, then assert

Make the database do the work:

@Test
void rejectsDuplicateEmail() {
    em.persist(new Customer("Ada", "ada@example.com"));
    em.flush();

    assertThatThrownBy(() -> {
        em.persist(new Customer("Ada Two", "ada@example.com"));
        em.flush();
    }).isInstanceOf(PersistenceException.class);   // jakarta.persistence; Hibernate's exception, untranslated
}
java

Both the persist and the flush sit inside the lambda because, with IDENTITY ids, Hibernate sends the INSERT at persist time; with sequence ids it waits for the flush. A version of this test that persists both customers without flushing and asserts nothing passes whether or not the unique constraint exists, because the inserts are discarded at rollback. Note that TestEntityManager.flush() goes straight to Hibernate, so you see Hibernate’s exception rather than Spring’s translated DataIntegrityViolationException; calling customers.saveAndFlush(...) through the repository proxy gives the translated one.

Two bugs an H2 test suite would approve

Picture a repository with a native query that finds customers by a tag stored in a PostgreSQL jsonb column, and a derived query for case-insensitive email lookup. Tests use @DataJpaTest with H2, and the native query test is marked @Disabled because H2 does not understand jsonb. Everything else passes.

Two bugs can reach production from this setup. First, a typo in a JSON operator in the native query goes unnoticed because nobody runs it. Second, a unique index on lower(email) exists in the Flyway migration, but the H2 tests use create-drop from entity annotations, which creates a plain case-sensitive unique constraint. Signing up with “Ada@x.com” and then “ada@x.com” passes in tests and fails with a constraint violation in production.

The fix is to switch the repository tests to the Testcontainers setup from Step 2, run the Flyway migrations, set ddl-auto=validate and re-enable the native query test. Both bugs then reproduce in the suite. The module’s tests get slower by the container’s startup time, which is paid once if the container is shared across classes through a common base configuration.

Repository tests that prove less than they seem

  • Asserting without flushing. You test Hibernate’s in-memory state, not the database.
  • Trusting H2 compatibility modes. MODE=PostgreSQL covers some syntax, not types such as jsonb, partial indexes or locking behaviour.
  • Expecting service beans in @DataJpaTest. They are excluded. Use @SpringBootTest for service-plus-repository tests, or construct the service with the repository manually.
  • Testing after-commit behaviour in a rolled-back test. Use @Transactional(propagation = NOT_SUPPORTED) on the test, or TestTransaction.flagForCommit() and TestTransaction.end(), and clean up yourself.
  • Letting ddl-auto=create-drop build the schema. The migrations are then never exercised, and the schema under test is Hibernate’s guess rather than production’s.

A test that only passes on the real database

Prove the slice really hits the database by checking a database-specific feature:

@Test
void uniqueIndexIsCaseInsensitive() {
    customers.saveAndFlush(new Customer("Ada", "Ada@example.com"));

    assertThatThrownBy(() -> customers.saveAndFlush(new Customer("Ada", "ada@example.com")))
            .isInstanceOf(DataIntegrityViolationException.class);
}
java

Against H2 with create-drop this test fails (the second save succeeds); against PostgreSQL with the Flyway lower(email) index it passes. That difference is the whole argument for database fidelity. Run ./mvnw test -Dtest=CustomerRepositoryPostgresTest and look for the Testcontainers startup log and Flyway’s “Successfully applied N migrations” line.

Other slices, shared containers and committing tests

What other test slices exist? Boot also ships @WebMvcTest, @WebFluxTest, @JsonTest, @RestClientTest, @JdbcTest, @DataMongoTest and others, and each loads only the auto-configuration for its layer.

How do you share a container across test classes? Declare it in a base class or interface with a static field, or use a @TestConfiguration that defines the container as a @Bean with @ServiceConnection; Spring’s context cache then reuses it.

Why might a @DataJpaTest miss your custom repository fragment’s dependencies? Fragments that inject non-JPA beans need those beans imported, since the slice excludes ordinary components.

When should a test commit? A test should commit when the behaviour under test only happens at commit: deferred constraints, after-commit listeners, or optimistic locking across two transactions.

Quiz yourself: why does this NOT NULL test pass?

A teammate’s repository test persists an order with a null customer_id, calls findById, and asserts the order is found. The column is NOT NULL in the migration. The test passes. Explain why and fix the test.

Answer and the fix

The persist only schedules an INSERT in the persistence context. findById in the same transaction returns the managed instance from the first-level cache without SQL, so the NOT NULL constraint is never checked. At the end, the test transaction rolls back and the insert is discarded unsent. Fix: call em.flush() after persisting (expect a constraint violation if the null is wrong), then em.clear() before reading so the read issues a real SELECT. Also make sure the test runs against the migration-built schema, ideally on the production engine through Testcontainers, so the constraint actually exists. The reasoning: a repository test must force the database to execute the SQL it claims to test.

Where to go next on Spring testing

More in Spring Boot

esc