Blog

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:
@Entity
public class Course implements Serializable {

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

@Entity
public class Clazz implements Serializable {
    
    @ManyToOne
    @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:
    course.getClasses().remove(clazz);  
    entityManager.remove(clazz);

No comments:

Post a Comment