Get JPA object id after merge?

I have a newly created object (separate, because it has not yet been saved to the database). This object has another entity that already exists in db (but also disabled). So I would use em.merge(myNewEntity) to save it.

If I want to get the newly created identifier, I would use em.flush() after that. Then I call myNewEntity.getId() . With persist I get the identifier generated by DB / JPA. This is not the case with merge . The object identifier remains null . Why is this?

+5
source share
1 answer

The result of the merge operation does not match the result of the persist operation - the object passed to merge does not become manageable. Rather, a managed copy of the object is created and returned. This is why the original new entity will not receive the identifier. So instead

 em.merge(newEntity); Long id = newEntity.getId(); 

it should be

 managedEntity = em.merge(newEntity); Long id = managedEntity.getId(); 
+16
source

Source: https://habr.com/ru/post/1205082/


All Articles