In this tutorial, you will learn a various ways to delete data using JPA/Hibernate Entity such as JPQL, CascadeType.REMOVE or CascadeType.ALL, and orphanRemoval. You will also learn to do JPA integration test in Spring Boot with in-memory database, @DataJpaTest and @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+

Project structure

Project dependencies


Define JPA Entity and Repository





Application Configuration



Integration test Deleting Data with JPA/Hibernate and @DataJpaTest


@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.
  • Using cascade = CascadeType.REMOVE or cascade = CascadeType.ALL to 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.
  • Using orphanRemoval if you need to delete the associated entities only.

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/jpa-hibernate-examples/jpa-hibernate-crud-deleting-entity