@DataJpaTest defines a focused Spring Boot test slice for the JPA data layer. It limits scanning to entities and associated repositories, loads data-related auto-configuration, replaces the default database with an in-memory database, and runs tests transactionally. section 5.1 section 5.6
Use the annotation when the data-layer boundary provides enough isolation and value:
- Test repositories and persistence behavior without loading the full application context. section 5.1
- Expect database changes to roll back after each test because the tests run inside transactions. section 5.6
- Prefer an existing @SpringBootTest context when repositories are already included and reusing its cached context avoids bootstrapping data infrastructure again. section 5.6
- Customize inclusion or exclusion filters only when the default JPA and Hibernate scanning does not provide the required context. section 5.7.2
Minimal data-layer slice
@DataJpaTest class RepositoryTest { // repository-focused tests } section 5.1 section 5.6
Figure 5.1 The three tier architecture. Each layer accesses the one below it. They have their own specific scope, with dedicated types, and both the presentation and data layers have dedicated testing infrastructure.
Use the architecture figure to locate @DataJpaTest alongside the dedicated testing infrastructure for the data layer. section 5.1
Listing 5.17 Dependencies for H2 or Derby
<!-- H2 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> <!-- Or Derby --> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <scope>test</scope> </dependency>
Use the dependency listing when the in-memory test database requires an H2 or Derby test dependency. section 5.6
