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();
source share