Type: New Feature
Affects Version/s: None
Fix Version/s: None
The EntityManager's persist method modifies its argument (the entity to be persisted) with generated data such as the Id.
The merge method can also be used to persist a new entity, but has the additional benefit that it can also update the entity or any of its relations in the DB. merge however does not modify its argument but returns a new instance in which the generated data such as the Id is set.
For some uses cases its needed to have the original entity instance be modified such as the persist method does, but with the semantics of the merge method.
For instance, in a JSF application an existing (persistent but detached) entity is passed into an action method to add a new entity into e.g. a @OneToMany relation. When the action method returns, rendering of the page begins, which still has a reference to the original entity. Depending on the backing bean and template structure of the page in question, it might not be trivial to have the action method replace this original reference that was passed into it, and the kind of update that persist does would be far more convenient.
For this I would like to request adding a variant of EntityManager#merge that modifies its argument instead of returning a new instance.
Alternatively a refresh method that accepts detached entities could also work for the above mentioned use case. Yet another alternative might be having an attach method that makes its argument attached, overwriting fields in that argument if an entity with the same identity happened to be present in the persistence context, but contrary to merge not updating any data in the database.