Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"detached entity passed to persist error" with JPA/EJB code

Tags:

java

jpa

ejb-3.0

I am trying to run this basic JPA/EJB code:

public static void main(String[] args){          UserBean user = new UserBean();          user.setId(1);          user.setUserName("name1");          user.setPassword("passwd1");          em.persist(user);   } 

I get this error:

javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.JPA.Database 

Any ideas?

I search on the internet and the reason I found was:

This was caused by how you created the objects, i.e. If you set the ID property explicitly. Removing ID assignment fixed it.

But I didn't get it, what will I have to modify to get the code working?

like image 200
zengr Avatar asked Mar 14 '10 08:03

zengr


People also ask

How do you resolve a detached entity passed to persist?

The solution is simple, just use the CascadeType. MERGE instead of CascadeType. PERSIST or CascadeType. ALL .

What is the meaning of detached entity passed to persist?

Detached Entities A detached entity is a Java object that is no longer tracked by the persistence context. Entities can reach this state if we close or clear the session.

What is detached entity?

A detached entity is just an ordinary entity POJO whose identity value corresponds to a database row. The difference from a managed entity is that it's not tracked anymore by any persistence context. An entity can become detached when the Session used to load it was closed, or when we call Session.


1 Answers

The error occurs because the object's ID is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects. If persist concludes the object is detached (which it will because the ID is set), it will return the "detached object passed to persist" error. You can find more details here and here.

However, this only applies if you have specified the primary key to be auto-generated: if the field is configured to always be set manually, then your code works.

like image 147
Tomislav Nakic-Alfirevic Avatar answered Oct 24 '22 14:10

Tomislav Nakic-Alfirevic