Java Persistence API detached object gotchas
One of the issues to get your head around in both Hibernate and JPA is how to handle detached entities. In Hibernate one has to deal with the session object and in JPA it is called the persistence context.
The most common solution is to re-attach your entities to a new persistence context when they need to be flushed to the database again. In JPA one uses the merge function to attached a detached object to the current persistence context. Lets say we have a person object and a company object, with a person belonging to a company. To reattached the detached person object one has to do: (em is a valid EntityManager object)
The mistake people often make, is that the merge function returns an new, ie separatet, attached object of the same type as the detached object and updated for the changes in the detached object. This object is not the same object as the detached instance you sent into the method. So the following will not work:
Instead you need to go:
person = em.merge(person)
The same applies for updating or merging an object with foreign entities. This approach is mandated by the JPA specification, although I am sure they had their reasons it is a cause of many lost hours in debugging when you first start trying out JPA.