Suppose I have an object A with id 1 on my persistence layer (i.e. on the DB)
If I do the following
A a = new A();
a.setId(1);
a.setSomeField("a value");
A managed_a = entityManager.merge(a);
would the entity manager retrieve the persisted entity with id 1 on the DB, make it managed, and update it accordingly ?
Or the object with id 1 has to exsist in the persistence context in order in order for the above to happen ?
The semantics of the merge operation applied to an entity X are as follows:
- If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
- If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
On the first point: If your entity A with an id of 1 is already existing in your database table, then that means entity A is a DETACHED entity. In that case, fields of entity A will be merged to the data in your table, thus you'll see this as an UPDATE operation.
On the second point: If your entity A with an id of 1 is not existing in your database table, then entity A is considered as NEW entity. Thus, this will be an INSERT operation.
Both scenarios lead to a managed entity returned from a merge operation.