Hibernate抛出无法删除或更新父行:外键约束失败 [英] Hibernate throws Cannot delete or update a parent row: a foreign key constraint fails

查看:150
本文介绍了Hibernate抛出无法删除或更新父行:外键约束失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个基本的例子来测试级联删除操作,但我收到异常。



I有以下实体:

Employee.java

  @Entity 
public class Employee {
@Id
@Column(name =EMP_ID)
private long id;

私人字符串名称;

@OneToMany(mappedBy =employee)
@Cascade(value = {CascadeType.REMOVE,CascadeType.SAVE_UPDATE})
private List< EmpDetails> details = new ArrayList< EmpDetails>();

$ b $ / code>

EmpDetails.java p>

  @Entity 
公共类EmpDetails {
@Id
私人长ID;
private int info;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name =EMP_ID)
私人员工雇员;





现在我拥有员工ID为10的数据库记录和员工相应的记录详细信息表。



现在,当我运行以下查询时:

 会话.beginTransaction(); 

session.delete(新员工(10)); //这里10是员工的ID

session.getTransaction()。commit();
session.close();

我以为hibernate会删除员工记录和相应的员工详细记录,因为我已经设置了级联键入即可删除。但我收到的例外情况如下:


造成:
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException:
无法删除或更新父行:外键约束失败


有人可以帮助我如何测试级联删除选项吗?

解决方案

删除级联类型用于标准JPA remove()操作。对于本地Hibernate delete()操作,您需要使用 Hibernate-proprietary annotation

  @ Cascade(CascadeType.DELETE)


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

这篇关于Hibernate抛出无法删除或更新父行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆