Sub topic 9
Testing repositories with @DataJpaTest
This chapter assumes you can write a Spring Data JPA repository, know what an entity is, and have read the earlier chapters on test slices and spring-boot-starter-test. It covers what @DataJpaTest loads, how its transactions behave, how to run it against a real database, and the errors people hit most often.
What a repository test should prove
A repository interface such as GreetingRepository has almost no code of its own. Spring Data generates the implementation at startup. So a repository test does not check Java logic. It checks that the following parts work together:
- The entity mapping (table names, column types, relationships).
- Derived query methods such as
findByName. - Custom
@Querystrings in JPQL or native SQL. - Constraints such as unique keys and non-null columns.
- Schema creation or migration scripts.
If a repository has only inherited methods like save and findById, a test adds little value. Test the methods you wrote: derived queries with several conditions, custom queries, and anything that depends on database behavior.
What @DataJpaTest loads
@DataJpaTest is a test slice. It starts a Spring context that contains only the persistence layer:
- Entity scanning and Spring Data JPA repositories.
- The
DataSource,EntityManagerFactory, and transaction manager. TestEntityManager, a helper for setting up and inspecting data.- Flyway or Liquibase, if they are on the classpath.
It does not load @Controller, @Service, or @Component beans. A service that depends on your repository will not exist in this context, which keeps the test fast and focused.
By default it also replaces your configured DataSource with an embedded database (H2, HSQLDB, or Derby) if one is on the classpath. It sets spring.jpa.show-sql to true, so you see the generated SQL in the output. If no embedded database is available, the test fails at startup.
A first repository test
Assume this entity and repository:
@Entity
public class Greeting {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name;
@Column(nullable = false)
private String message;
protected Greeting() {
}
public Greeting(String name, String message) {
this.name = name;
this.message = message;
}
public String getName() {
return name;
}
public String getMessage() {
return message;
}
}public interface GreetingRepository extends JpaRepository<Greeting, Long> {
Optional<Greeting> findByName(String name);
}A test with the default embedded database:
@DataJpaTest
class GreetingRepositoryEmbeddedTest {
@Autowired
GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
@Test
void returnsEmptyForUnknownName() {
assertThat(repository.findByName("Nobody")).isEmpty();
}
}The second test does not see the row saved by the first. The reason is the transaction rule described next.
Transactions and rollback
Every @DataJpaTest test method runs inside a transaction, and Spring rolls that transaction back when the method ends. You get a clean database for each test without writing cleanup code.
This is convenient, but it has a side effect you must understand. Inside one transaction, Hibernate does not write to the database at once. It keeps changes in the persistence context (its first-level cache) and sends SQL on flush, on commit, or before a query that needs the data. Because the test never commits, three things follow:
- A constraint violation may not appear until a flush happens. A test that saves a duplicate name can pass if nothing forces the SQL to run.
findByIdright aftersavereturns the cached object, not a fresh row from the database. It can hide a mapping error.- Generated SQL for
IDENTITYids runs atsave, but SQL for other strategies may be delayed.
To test what the database actually does, flush and clear the persistence context. TestEntityManager makes this short:
@DataJpaTest
class GreetingConstraintTest {
@Autowired
TestEntityManager entityManager;
@Autowired
GreetingRepository repository;
@Test
void loadsFreshRowFromDatabase() {
Greeting saved = entityManager.persistAndFlush(new Greeting("Ada", "Hello, Ada"));
entityManager.clear();
Greeting loaded = repository.findById(saved.getId()).orElseThrow();
assertThat(loaded).isNotSameAs(saved);
assertThat(loaded.getMessage()).isEqualTo("Hello, Ada");
}
@Test
void rejectsDuplicateName() {
entityManager.persist(new Greeting("Ada", "Hello"));
assertThatThrownBy(() -> entityManager.persistAndFlush(new Greeting("Ada", "Hi")))
.isInstanceOf(PersistenceException.class);
}
}persistAndFlush writes the row immediately. clear detaches all entities, so the next read goes to the database. The unique constraint test uses a flush to force the violation. Depending on the Hibernate version, the exception can be PersistenceException or a subclass such as ConstraintViolationException wrapped inside it, so assert on the broad type unless you need the detail.
If a test needs a real commit, for example to check behavior across two transactions, annotate it with @Commit or disable the wrapping transaction with @Transactional(propagation = Propagation.NOT_SUPPORTED). Then you are responsible for cleaning up the data.
Why the embedded database can mislead you
H2 is fast, but it is not your production database. Differences that cause tests to pass while production fails:
- Native queries that use PostgreSQL features (
jsonb,ILIKE, array types,ON CONFLICT). - Differences in case sensitivity, sorting, and null ordering.
- Column type mappings and default values.
- Locking and isolation behavior.
- Schema produced by Hibernate (
create-drop) instead of your real migration scripts.
If your repository uses any of these, run the test against the same database engine you deploy. H2's compatibility modes reduce the gap but do not remove it.
Using a real database with Testcontainers
Testcontainers starts a Docker container for the test. Docker must be running on the machine. Add the dependencies (versions are managed by Spring Boot's dependency management for the Boot-aware modules):
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
runtimeOnly 'org.postgresql:postgresql'
}Then write the test:
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class GreetingRepositoryTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@Autowired
GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}Each annotation has one job:
| Annotation | Purpose |
|---|---|
| `@Testcontainers` | Enables the JUnit 5 extension that starts and stops `@Container` fields. |
| `@Container` on a `static` field | Starts one container for all tests in the class. A non-static field starts a new container for every test method. |
| `@ServiceConnection` | Tells Spring Boot to build the `DataSource` connection details from the running container. No `@DynamicPropertySource` is needed. |
| `@AutoConfigureTestDatabase(replace = NONE)` | Stops `@DataJpaTest` from swapping in an embedded database. |
Without the replace = NONE setting, the test would silently use H2 and ignore your container. That is the most common mistake with this setup.
Schema creation
In a @DataJpaTest, Hibernate's ddl-auto defaults to create-drop for embedded databases and none otherwise. With a container, the default is therefore none, and the tables will not exist unless something creates them. You have two choices:
- Use Flyway or Liquibase. The migrations run against the container at startup, so the test uses the real schema. This is the better option because it also tests your migrations.
- Set
spring.jpa.hibernate.ddl-auto=create-dropin the test, for example with@DataJpaTest(properties = "spring.jpa.hibernate.ddl-auto=create-drop"). This is quick but skips your migration scripts.
Testing a custom query
Here is a custom JPQL query and a test that proves its filter and ordering:
public interface GreetingRepository extends JpaRepository<Greeting, Long> {
Optional<Greeting> findByName(String name);
@Query("select g from Greeting g where lower(g.name) like lower(concat(:prefix, '%')) order by g.name")
List<Greeting> searchByPrefix(@Param("prefix") String prefix);
}@Test
void searchesByPrefixIgnoringCase() {
repository.save(new Greeting("Ada", "Hello, Ada"));
repository.save(new Greeting("adam", "Hi, Adam"));
repository.save(new Greeting("Grace", "Hello, Grace"));
List<Greeting> result = repository.searchByPrefix("AD");
assertThat(result).extracting(Greeting::getName).containsExactly("Ada", "adam");
}Give the test data that can fail the query in more than one way: a row that should match, rows that should not, and rows that differ only by case. A single matching row proves almost nothing.
Sharing one container across test classes
A static container per class starts a fresh database for each class, which is slow when you have many repository tests. A common fix is a shared configuration that declares the container as a bean:
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>("postgres:16");
}
}Add @Import(ContainersConfig.class) to the tests that need it. Spring's context cache then reuses the same context, and the same container, across those classes. The cache is covered in a later chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Test passes but production query fails | Test ran on H2 | Use Testcontainers with the production engine |
| `Table not found` with a container | `ddl-auto` is `none` and no migration ran | Add Flyway/Liquibase or set `create-drop` |
| `No qualifying bean of type` for a service | `@DataJpaTest` does not load services | Test the service separately, or `@Import` it deliberately |
| Constraint test never fails | No flush before the assertion | Use `persistAndFlush` or `repository.flush()` |
| Reads return stale objects | Persistence context cache | Call `entityManager.clear()` before reading |
| `Could not find a valid Docker environment` | Docker is not running | Start Docker, or skip container tests in that environment |
| Data leaks between tests | `@Commit` or a non-transactional test | Remove it, or clean up explicitly |
Exercise
A @DataJpaTest with a PostgreSQL Testcontainer saves a Greeting whose name duplicates an existing row, then asserts that an exception is thrown. The test fails because no exception occurs. The unique constraint exists in the schema. What is the most likely cause, and how do you fix it?
Show answer
The test runs inside a transaction that is rolled back, and Hibernate has not yet sent the INSERT to the database, so the constraint is never checked. Force the SQL to run by calling entityManager.persistAndFlush(...) or repository.saveAndFlush(...) inside the assertion. The flush sends the INSERT and the database raises the violation.
Exercise
You added @Container @ServiceConnection to a PostgreSQL container in a @DataJpaTest, but the test logs show H2 being used. What is missing?
Show answer
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE). By default @DataJpaTest replaces the DataSource with an embedded database, so the container connection is ignored until you turn the replacement off.