Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
learner Avatar asked Aug 21 '15 18:08

learner


People also ask

How do you delete child records when parent is deleted in hibernate?

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.


2 Answers

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)
like image 126
JB Nizet Avatar answered Nov 07 '22 12:11

JB Nizet


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;
}
like image 45
besartm Avatar answered Nov 07 '22 11:11

besartm