Adding a detached entity to a managed entity's collection triggers an exception on flush

Description

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:

Environment

None

Activity

Show:
Réda Housni Alaoui
October 14, 2015, 2:56 PM

Test case added as

Réda Housni Alaoui
October 14, 2015, 3:42 PM

The interesting thing is that if we save before we flush, there is no exception.

Gail Badner
February 17, 2016, 2:36 AM

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."

Gail Badner
February 17, 2016, 2:36 AM

Expected behavior.

Assignee

Gail Badner

Reporter

Réda Housni Alaoui

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

Priority

Critical
Configure