I have a freshly created entity (detached because not yet saved in the DB). This entity holds another entity that already exists in the db (but is detached, too). Thus, I would use em.merge(myNewEntity)
to store it.
If I want to get the new created ID, I would use em.flush()
afterwards. Then I invoke myNewEntity.getId()
. With persist
I receive an ID generted by the DB/JPA. With merge
, it does not. The ID in the object remains null
. Why is that?
The result of the merge
operation is not the same as with the persist
operation - the entity passed to merge
does not become managed. Rather, a managed copy of the entity is created and returned. This is why the original new entity will not get an id. So instead of
em.merge(newEntity);
Long id = newEntity.getId();
it should be
managedEntity = em.merge(newEntity);
Long id = managedEntity.getId();
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