java / intermediate
Snippet
Isolating Repository Persistence Slices Using TestEntityManager
@DataJpaTest configures an isolated test slice focusing exclusively on JPA components, bypassing full web server and service loading. TestEntityManager provides an alternative to the standard JPA EntityManager specifically designed for tests. It allows developers to persist, flush, and clear the persistence context explicitly, ensuring queries executed by the repository under test hit the database rather than resolving entities from the first-level session cache.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)class OrderRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate OrderRepository orderRepository;@Testvoid shouldFindActiveOrdersByCustomerCode() {Customer customer = entityManager.persistFlushFind(new Customer("CUST_100"));Order order = new Order("ORD_99", OrderStatus.ACTIVE, customer);entityManager.persistAndFlush(order);entityManager.clear();List<Order> activeOrders = orderRepository.findByCustomerCodeAndStatus("CUST_100", OrderStatus.ACTIVE);assertThat(activeOrders).hasSize(1);assertThat(activeOrders.get(0).getOrderNumber()).isEqualTo("ORD_99");}}
spring
Breakdown
1
@DataJpaTest
Boots only Spring Data JPA repositories, entities, and DataSource beans for efficient integration testing.
2
Customer customer = entityManager.persistFlushFind(new Customer("CUST_100"));
Persists an entity, flushes changes immediately to the database, and returns the managed instance.
3
entityManager.clear();
Clears the Hibernate first-level cache to ensure subsequent repository calls test genuine SQL generation.