Sub topic 17
Testing repositories with @DataJpaTest
This chapter assumes you can write entities and repository interfaces as shown earlier in this tutorial, and that you know JUnit 5 and AssertJ basics. It covers what @DataJpaTest sets up, how to write repository tests that hit the database, and the mistakes that make a passing test meaningless.
What @DataJpaTest starts
@DataJpaTest is a test slice. It starts a Spring context that contains only the persistence layer, not the whole application.
- It scans for
@Entityclasses and creates Spring Data repositories. - It configures Hibernate, a
DataSource, a transaction manager and aTestEntityManager. - It does not create
@Service,@Controlleror@Componentbeans. - By default it replaces your configured database with an embedded one (H2, HSQLDB or Derby) found on the classpath.
- It wraps every test method in a transaction and rolls it back when the method ends.
The rollback means tests do not need cleanup code, and tests cannot see each other's data.
A first repository test
You need a repository for Author, which the test uses to save data.
import org.springframework.data.jpa.repository.JpaRepository;
public interface AuthorRepository extends JpaRepository<Author, Long> {
}The test saves an author with two books through the cascade on Author.books, then calls the paged derived query.
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.data.domain.PageRequest;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class BookRepositoryTest {
@Autowired
private AuthorRepository authors;
@Autowired
private BookRepository books;
@Test
void findsBooksPublishedFromGivenYear() {
Author author = new Author("Ursula K. Le Guin");
author.addBook(new Book("A Wizard of Earthsea", 1968));
author.addBook(new Book("The Dispossessed", 1974));
authors.save(author);
var page = books.findByPublishedYearGreaterThanEqual(1970, PageRequest.of(0, 10));
assertThat(page.getContent()).extracting(Book::getTitle)
.containsExactly("The Dispossessed");
}
}The test calls author.addBook(...) instead of books.add(...) so both sides of the association stay in sync. Because Book.author is the owning side and is optional = false, a book without an author would fail on insert.
Flush and clear: making the test hit the database
A repository test can pass without ever testing your query's SQL. The persistence context is a first-level cache. If you save an entity and then load it in the same transaction, Hibernate may return the cached object and never read a row from the database.
Two operations fix this:
flush()sends pending SQL statements to the database.clear()detaches all entities, so later reads must go back to the database.
TestEntityManager is a thin wrapper around EntityManager for tests. It exposes persist, flush, clear and find.
import org.hibernate.Hibernate;
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 BookFetchTest {
@Autowired
private TestEntityManager em;
@Autowired
private BookRepository books;
private void givenOneBookFrom1974() {
Author author = new Author("Ursula K. Le Guin");
author.addBook(new Book("The Dispossessed", 1974));
em.persist(author);
em.flush();
em.clear();
}
@Test
void joinFetchInitializesAuthor() {
givenOneBookFrom1974();
List<Book> result = books.findByYearWithAuthor(1974);
assertThat(result).hasSize(1);
assertThat(Hibernate.isInitialized(result.get(0).getAuthor())).isTrue();
}
@Test
void derivedQueryLeavesAuthorLazy() {
givenOneBookFrom1974();
List<Book> result = books.findByTitleContainingIgnoreCase("dispossessed");
assertThat(result).hasSize(1);
assertThat(Hibernate.isInitialized(result.get(0).getAuthor())).isFalse();
}
}The second test documents the lazy default. The first proves that join fetch loads the author in the same select. Hibernate.isInitialized checks a proxy without triggering a load, so the assertion itself does not cause the extra select.
Why IDENTITY hides some problems
The entities in this tutorial use GenerationType.IDENTITY. Hibernate must run the insert immediately to learn the generated id, so the insert happens at save() time. A constraint violation, such as a null in a nullable = false column, fails right away.
With SEQUENCE generation, inserts are delayed until flush. In that case, a test that never flushes will not see a constraint violation, because the rollback discards the statements unexecuted. If you switch strategies later, add an explicit flush() to tests that check constraints.
Choosing the database
The embedded database is fast but differs from production. Differences show up in native queries, JSON columns, case sensitivity and sequence behavior. You have three options.
| Option | Setup | Trade-off |
|---|---|---|
| Embedded H2 (default) | Add the H2 dependency with test scope | Fast, but SQL dialect and behavior can differ from production |
| H2 in a compatibility mode | Set `MODE=PostgreSQL` or similar in the test URL | Closer to production, still not the same engine |
| Testcontainers with the real database | Needs Docker | Most faithful, slower start |
Tests that run native @Query methods should use the real engine. To keep your configured datasource, disable the replacement. The example below uses Testcontainers with Spring Boot 3.1 or later and @ServiceConnection, which wires the container's URL and credentials into the datasource.
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
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:16");
// test methods as before
}The @Container field is static, so one container serves all tests in the class.
Common errors
NoSuchBeanDefinitionExceptionfor a service. The slice does not load@Servicebeans. To test a service together with its repositories, add@Import(CatalogService.class). Otherwise, test the service with a unit test or@SpringBootTest.- Schema not created, or an unexpected schema. The slice defaults to
spring.jpa.hibernate.ddl-auto=create-dropfor embedded databases. If you use Flyway or Liquibase, the migrations run instead, and the entity mapping must match them. A mismatch fails at startup or on the first query. - Test passes but production fails with
LazyInitializationException. The test transaction keeps the session open for the whole method, so lazy loading always works in the test. Check laziness withHibernate.isInitialized, as in the example above, instead of relying on a call that would silently load the data. - Testing
@Transactionalservice behavior. Because the test already holds a transaction, a service method that expects to start its own transaction joins the test's transaction instead. Commit behavior and rollback on exception are not realistic here. Mark such a test@Transactional(propagation = Propagation.NOT_SUPPORTED)and clean the data yourself, or use@SpringBootTest. - Testing Spring Data's own methods. Do not test
saveorfindById. Test derived queries with non-trivial names,@Querymethods, cascade and orphan removal, and constraints you rely on.
Checking the N+1 problem in a test
You can assert that a query issues a fixed number of statements. Set spring.jpa.properties.hibernate.generate_statistics=true in the test properties, then read Statistics#getPrepareStatementCount() from the SessionFactory. Call statistics.clear() before the query under test. A query with join fetch or an @EntityGraph should show one prepared statement, while a loop that touches each book's author shows one extra per author. This turns the N+1 problem into a regression test.
Exercise
A test saves an Author with one Book using authors.save(author), then calls books.findByTitleContainingIgnoreCase("earth") and asserts that result.get(0).getAuthor() is not null. The test passes, but a colleague says it proves nothing about lazy loading. What is wrong, and what two calls fix it?
Show answer
The save and the query run in the same persistence context, so the query returns the same Book instance that was just saved. Its author field is already a real, loaded object, not a lazy proxy. Calling flush() and then clear() on the TestEntityManager (or EntityManager) before the query forces the database read and a fresh Book with an uninitialized author proxy. After that, Hibernate.isInitialized(book.getAuthor()) shows the true lazy state.