How do I get id of merged JPA entity
I have a little application where I store entity to DB. I do this in next way:
class Entity {
privete id;
String somePropertie;
// getters and setters
}
// In main class
Entity newEntity = new Entity();
newEntity.setSomePropertie("somePropertie");
Entity entity = entityManager.merge(newEntity);
System.out.println("This is id of 开发者_如何学Cstored entity:", entity.getId())
The didn't write the jpa annotations here. But the entity is stored to database, but the printed id is 0; I using transaction driven by spring, I need this entity for later updates of the entity id.
EntityManager.merge(..) gets an instance and returns an instance that is managed. And in case of transient instances it returns a new instance (does not modify the original)
So your mergeEntity(..) method should return em.merge(entity)
Correct me if I am wrong, but have you tried with
Entity entity = entityManager.merge(newEntity);
System.out.println("This is id of stored entity:", entity.getId())
in the same transaction?
Also try setting id to Long
rather than long
(or Integer
rather than int
; it is not clear from your definition)
精彩评论