JPA Cascade Remove
The cascade remove is used to specify that if the parent entity is removed then all its related entities will also be removed. The following syntax is used to perform cascade remove operation: -
Cascade Remove Example
In this example, we will create two entity classes that are related to each other but to establish the dependency between them we will perform cascading operation.
This example contains the following steps: -
- Create an entity class named as StudentEntity.java under com.javatpoint.jpa.student package that contains attributes s_id, s_name, s_age and an object of Subject type marked with cascade specification.
- Create another entity class named as Subject.java under com.javatpoint.jpa.subject package.
- Now, map the entity class and other databases configuration in Persistence.xml file.
- Create a persistence class named as StudentCascade.java under com.javatpoint.jpa.cascade package to persist the entity object with data.
After the execution of the program, the following tables are generated under MySQL workbench.
- Student table - The details of student having s_id 101 will be removed from student table. To fetch data, run select * from student query in MySQL.
- Subject table - Due to cascade remove, the details related to s_id 101 will also be deleted from subject table. To check the result, run select * from subject query in MySQL