Question

My setup involves glassfish4 and objectDB but I believe my question is general JPA.

Assume you a function that gets an entity as parameter. This entity is detached but holds the most current state of the entity. (This could i.e. when somebody has updated the values of an entity through a gui, or you get the latest data from another system.)

The goal is to store this new data in the DB. You don't want to simply add this entity (i.e. because some unique constraints will punish this) but you want to update the old version of the entity that is stored in the DB.

How do you do this?

One idea I had was to retrieve the ID and Version from the DB instance, copy them into the detached instance and then merge this instance.

MyEntity storedEntity = myEntityDao.findEntityFor(newEntity);
newEntity.setId(storedEntity.getId());
newEntity.setVersion(storedEntity.getVersion());
MyEntity mergedEntity = em.merge(newEntity);

But the version field is not correct. (ObjectDB throws an OptimisticLockException, no matter if I add +1 or +5 to the version during the assignment.)

Was it helpful?

Solution

The correct way is to ensure that the Id and the version of the stored entity was never changed during it's roundtrip to other parts of the application.

Then take that detached storedEntity, and call merge on it:

YourEntity attachedEntity = entityManager.merge(storedEntity);

You can make further changes to the entity after attachment by using the attached entity reference, not the original storedEntity detached copy.

In general the version field should not be modified by the application, Hibernate will handle this. At most this field can be copied around between entities and DTOs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top