In this tutorial, you will learn a various ways to delete data using JPA/Hibernate Entity such as
orphanRemoval. You will also learn to do JPA integration test in Spring Boot with in-memory database,
@DirtiesContext. Let's start building an example with Spring Boot and Spring Data JPA
What you will need
- JDK 8+ or OpenJDK 8+
- Maven 3+
- MySQL Server 5+ or Docker CE 18+
Define JPA Entity and Repository
Integration test Deleting Data with JPA/Hibernate and
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) reset the test environment context after each test method
Keys to take away
- Using JPQL, you don't need retrieve the data before deletion, hence this is a best approach for bulk delete.
cascade = CascadeType.REMOVEor
cascade = CascadeType.ALLto delete the associated entities when deleting the relationship owner. JPA/Hibernate will delete one-by-one so considering the performance tradeoff when using this option.
orphanRemovalif you need to delete the associated entities only.