Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get entity JPA Id after merge?

Tags:

jpa

jpa-2.0

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?

like image 960
feder Avatar asked Oct 20 '14 10:10

feder


Video Answer


1 Answers

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();
like image 94
kostja Avatar answered Oct 08 '22 09:10

kostja