I am working on a basic example to test cascade delete
operation but I am getting exception.
I have below entities:
Employee.java
@Entity
public class Employee {
@Id
@Column(name = "EMP_ID")
private long id;
private String name;
@OneToMany(mappedBy = "employee")
@Cascade(value = { CascadeType.REMOVE, CascadeType.SAVE_UPDATE })
private List<EmpDetails> details = new ArrayList<EmpDetails>();
}
EmpDetails.java
@Entity
public class EmpDetails {
@Id
private long id;
private int info;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "EMP_ID")
private Employee employee;
}
Now I have records in databse with employee id as 10 and corresponding records in employee details table.
Now when I run below query:
session.beginTransaction();
session.delete(new Employee(10)); // here 10 is the ID of the employee
session.getTransaction().commit();
session.close();
I was thinking hibernate will delete the employee record and the corresponding employee details records as I have set the cascade type to remove. But I am getting exception as :
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
Can someone please help me how to test the cascade delete option here?
The correct way is to create the foreign key on mail to reference account . With ON DELETE CASCADE , you tell MySQL that it should delete a row (whose table has the foreign key) if its parent (referenced by the key) is deleted.
The REMOVE cascade type is for the standard JPA remove()
operation. For the native Hibernate delete()
operation, you need to use a Hibernate-proprietary annotation:
@Cascade(CascadeType.DELETE)
When you delete Employee on session try to add this, I had the same issue:
session.delete(session.get(Employee.class, employee_Id));
On my issue I had Movie and TimeTable relation was OneToOne:
On Movie model:
public class Movie implements Serializable
{
@Id
@Column(name = "fid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int fid;
....
@OneToOne(mappedBy = "movie", cascade = CascadeType.ALL, orphanRemoval = true)
private TimeTable timetable;
}
On TimeTable model:
public class TimeTable implements Serializable
{
...
@OneToOne
@JoinColumn(name = "fid")
private Movie movie;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With