[英]Hibernate throws Cannot delete or update a parent row: a foreign key constraint fails
I am working on a basic example to test cascade delete
operation but I am getting exception.我正在编写一个基本示例来测试
cascade delete
操作,但出现异常。
I have below entities:我有以下实体:
Employee.java雇员.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 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.现在我在数据库中有记录,员工 ID 为 10,员工详细信息表中有相应的记录。
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.我在想 hibernate 会删除员工记录和相应的员工详细信息记录,因为我已将级联类型设置为删除。 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
引起:com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException:无法删除或更新父行:外键约束失败
Can someone please help me how to test the cascade delete option here?有人可以帮我在这里测试级联删除选项吗?
The REMOVE cascade type is for the standard JPA remove()
operation. REMOVE 级联类型用于标准 JPA
remove()
操作。 For the native Hibernate delete()
operation, you need to use a Hibernate-proprietary annotation :对于本机 Hibernate
delete()
操作,您需要使用Hibernate-proprietary annotation :
@Cascade(CascadeType.DELETE)
When you delete Employee on session try to add this, I had the same issue:当您在会话中删除 Employee 尝试添加此内容时,我遇到了同样的问题:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.