I have the following relationships defined
Entity A has @OneToMany with Entity B that has @OneToOne with Entity C.
At the time of creation for Entity A, I also create Entity B and set the relationship between them. Everything works as expected.
In another transaction,
– Entity A is fetched from the DB, the corresponding Entity B is fetched and then
– Entity C is created.
– Entity C is set on Entity B to forge the relationship between the two.
If i use EntityManager.persist(Entity B), the persistence manager tries and inserts Entity B into the DB again causing a unique constraint violation on the PK of Entity B.
If i user EntityManager.merge(Entity B), everything works as desired.
In this above context of use, why would a persist operation try and create a duplicate since the Entity is managed in this case and it should easily be able to do an update.
JPA requires providers to throw an exception if persist is called on an unmanaged instance. Only merge can be used since it is clear that it takes the data from the instance and merges it into a managed copy. If B were managed, the persist call would be ignored, so it means that some how B gets detached or that it was read in a different entityManager from the one you call persist on.