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?
The error occurs because the object's ID is set. Hibernate distinguishes between transient and detached objects and
persist
works only with transient objects. Ifpersist
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.
Here .persist() only will insert the record.If we use .merge() it will check is there any record exist with the current ID, If it exists, it will update otherwise it will insert a new record.
I got the answer, I was using:
I used merge in place of persist:
But no idea, why persist didn't work. :(
Another reason for error that your entity object doesn't implement
Serializable
interfaceI know its kind of too late and proly every one got the answer. But little bit more to add to this: when GenerateType is set, persist() on an object is expected to get an id generated.
If there is a value set to the Id by user already, hibernate treats it as saved record and so it is treated as detached.
if the id is null - in this situation a null pointer exception is raised when the type is AUTO or IDENTITY etc unless the id is generated from a table or a sequece etc.
design: this happens when the table has a bean property as primary key. GenerateType must be set only when an id is autogenerated. remove this and the insert should work with the user specified id. (it is a bad design to have a property mapped to primary key field)
I had this problem and it was caused by the second level cache:
Hence, because the cache wasn't invalidated, hibernate assumed that it was dealing with a detached instance of the same entity.