简体   繁体   中英

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.

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)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM