tags:

views:

1228

answers:

2

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?

+1  A: 

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

zengr
+2  A: 

The error you described 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.

Tomislav Nakic-Alfirevic
Will I be technically right when I say, I am using JPA and not Hibernate so, that above statement should not apply right? I am newbie in JPA (3 ays to be precise :P)
zengr
Sun's JPA Javadoc (http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#persist(java.lang.Object)) and that of Toplink are exactly the same and suggest you are technically right. However, it really boils down to what the specification says persist() should behave like and sadly, I don't know what that is.
Tomislav Nakic-Alfirevic