开发者

How to find out efficiently the auto-generated id for a new object when using JPA?

开发者 https://www.devze.com 2022-12-27 22:20 出处:网络
I have an attribute which is annotated with @Id. The ID is going to be generated automatically when persisting the object. That means that the ID-value is not defined before I persist the object. Afte

I have an attribute which is annotated with @Id. The ID is going to be generated automatically when persisting the object. That means that the ID-value is not defined before I persist the object. After persisting it, it has an ID (in the database), bu开发者_如何学运维t unfortunately the field still remains null as long as I don't reload it from the DB. is there any easy way to find out the generated id? Or better: To configure that it will be written into the field?

Thanks in advance


The id gets assigned after the flush. Assuming the Foo entity has an id attribute annotated with the standard @Id @GeneratedValue annotations, the following code works:

Foo foo = new Foo();
//...
em.persist(foo);
em.flush();
assert foo.getId() != null;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号