Is it correct that I never need to use EntityManager#merge()
, as long as I only deal with attached managed entities? In other words, calling merge()
on an attached managed entity has no effect?
Or are there circumstances where merging would serve a purpose? I find the name suggests that I could use it to deal with an OptimisticLockException
... :)
Edit: In very simple terms, my understanding of a managed Entity is that modifications of its properties/fields get persisted to the DB at the end of the transaction.
Persist takes an entity instance, adds it to the context and makes that instance managed (i.e. future updates to the entity will be tracked). Merge returns the managed instance that the state was merged with. It does return something that exists in PersistenceContext or creates a new instance of your entity.
JPA's merge method copies the state of a detached entity to a managed instance of the same entity. Hibernate, therefore, executes an SQL SELECT statement to retrieve a managed entity from the database.
persist(Object entity): Make an instance managed and persistent. merge(T entity): Merge the state of the given entity into the current persistence context.
update, attach the passed entity to the persistence context while EntityManager. merge method copies the state of the passed object to the persistent entity with the same identifier and then return a reference to that persistent entity. The object passed is not attached to the persistence context.
The specification states that:
If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With