EntityManager tries to insert objects without a request

I might simplify this too much by only providing you with a small snippet of code (and I will post more if that is the case), but I believe that the initial step is better:

I have an object of type Asset that has a field of type Location, which is also an entity. When I set the location of an object, I must also set the location of its children.

Location location = asset.getLocation();
em.merge(location);
em.flush();

childAsset.setLocation(asset.getLocation());
em.flush();

When I run flush (), I get the following exception:

Internal exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SWRADMIN.LOCATION_PK) violated

My question is: why is this Location object even trying to be saved? All I do is set a variable in the entity.

This worked well before, but we just switched to using Eclipselink and Java EE 6, and this problem arose.

Solution: I used the idea of ​​"disconnecting" from below and made the following change:

Location location = asset.getLocation();

em.detach(childAsset);
childAsset.setLocation(asset.getLocation());
em.merge();
em.flush();

and it worked! I am confused why, though ... you think auto-sync will do the same.

+1
source share
3 answers

If the object is in a managed state, then the object manager will synchronize it with the database, storing the object implicitly (possibly at the end of the transaction) or explicitly when you call the method em.flush().

You can use em.detach(entity)to detach a single object or em.clear()to detach all objects. Then, changes made to the entity / objects will not be displayed in the database.

, BMT (Bean Managed Transaction), , .

:

Location location = asset.getLocation();
childAsset.setLocation(location);
em.merge(childAsset);
em.flush();
+2

, - ?

, - ? , () .

, , .

0

, , ChildAsset. childAsset- > Location cascade persist, , perist Location on flush commit. Location , .

(, ChildAsset , em.merge(); ), ChildAsset- > Location - -op.

, cascade persist.

0

All Articles