Hibernate : How to resolve “org.hibernate.PersistentObjectException: detached entity passed to persist” error ?

This error may occur in two situations, look below:

Do you have an object and one of his attributes has the value an another object. This other object are detached, so don’t have more data from this other object in the hibernate proxy. In this situation only has the index value. To solve this you need take this object again by the primary key value, and for do this you can:

1 – Use Hibernate.initialize ();

Example: Hibernate.initialize (myFirstObj.getOtherObj ());

2 – Fetch the data:

Example:

myFirstObj.setOtherObj ( this.objService.findByPk( myFirstObj.getOtherObj().getPk() ));

There is also another very common situation, you are using a @ManyToOne mapping wrong and you put cascate settings. You should not use cascate in these situations, because for this type of mapping the actions to persist and to merge are automatic.

Example :

WRONG WAY :

@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})

RIGHT WAY

@ManyToOne

4 Comments

  1. I like the valuable information you provide in your articles. I will bookmark your blog and check again here regularly. I am quite certain I will learn many new stuff right here! Best of luck for the next!

    Like

Leave a reply to oakley batwolf sunglasses specs Cancel reply