如何获取合并的 JPA 实体的 id
我有一个小应用程序,将实体存储到数据库中。我用下面的方式做到这一点:
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 stored entity:", entity.getId())
这里没有写 jpa 注释。但实体存入数据库,但打印的id为0;我使用 spring 驱动的事务,我需要这个实体来稍后更新实体 id。
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 stored 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EntityManager.merge(..) 获取一个实例并返回一个被管理的实例。如果是瞬态实例,它会返回一个新实例(不会修改原始实例),
因此您的 mergeEntity(..) 方法应该返回 em.merge(entity)
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)
尝试过
如果我错了,请纠正我,但是您是否在同一笔交易中
?还可以尝试将 id 设置为
Long
而不是long
(或Integer
而不是int
;从您的信息中还不清楚定义)Correct me if I am wrong, but have you tried with
in the same transaction?
Also try setting id to
Long
rather thanlong
(orInteger
rather thanint
; it is not clear from your definition)