Let's assume we have the following entities:
Let's persist a tooth and a mouth containing an empty collection of teeth:
At this point, tooth is detached.
Now in a new session, let's retrieve the mooth instance from database and add tooth its teeth collection:
At this point, if we call em.flush the following exception is thrown:
Test case added as
The interesting thing is that if we save before we flush, there is no exception.
I believe this is expected. JPA 2.1 says this for flush operation:
"For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y."
JPA 2.1 says this for persist operation:
"If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time."