Friday 3 January 2014

Dreadful 'deleted entity passed to persist' exception

From time to time I encounter the following exception: 'javax.persistence.EntityNotFoundException: deleted entity passed to persist'. It's nasty because its stack trace doesn't suggest a source of the problem. Thankfully it's also very easy to fix.

The most common cause of the problem is that you're trying to remove from data base an object that is still referenced from parent's collection (usually annotated with @OneToMany(cascade = CascadeType.ALL)). Here is a quick sample of such relation:
public class Course implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "course")
    private List classes;

public class Clazz implements Serializable {
    @JoinColumn(name = "COURSE_ID")
    private Course course;

When you know what's causing the problem fixing it is very simple. You need to remove an object from parent's collection before deleting it in database:

No comments:

Post a Comment