Issue
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?
Solution
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)
Answered By - JB Nizet
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.