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

Init project structure and dependencies

Project structure

├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── hellokoding
│   │   │           ├── jpa
│   │   │           │   ├── book
│   │   │           │   │   ├── Book.java
│   │   │           │   │   ├── BookRepository.java
│   │   │           │   │   ├── Category.java
│   │   │           │   │   └── CategoryRepository.java
│   │   │           │   └── JpaApplication.java
│   │   │           └── springboot
│   │   └── resources
│   │       └── application.properties
│   └── test
│       └── java
│           └── com
│               └── hellokoding
│                   └── jpa
│                       └── book
│                           └── DeletingDataTest.java
├── Dockerfile
└── pom.xml

Project dependencies


Define JPA Entities and Repositories





Config and Test

Application Configuration



Integration test Deleting Data with JPA, Hibernate and @DataJpaTest


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 and 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

See also