简体   繁体   English

在休眠保存对象之前从序列获取生成的ID

[英]Get generated id from a sequence before hibernate saves the object

How do I get the generated ID for an object before hibernate saves it. 如何在休眠保存对象之前获取对象的生成ID。 Here's the code: 这是代码:

@Id
@SequenceGenerator(name="MY_SEQ", sequenceName="MY_SEQ", allocationSize=1 )
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MY_SEQ")
private long id;

Is there any way that I can do this without using a select on currval('MY_SEQ') ? 有什么办法可以在不使用currval('MY_SEQ')的情况下执行此操作?

Thanks 谢谢

Using the JPA @SequenceGenerator along with the legacy Hibernate identifiers will give you the SequenceHiLoGenerator that applies a HI/LO optimization algorithm anyway. 结合使用JPA @SequenceGenerator和传统的Hibernate标识符,将为您提供SequenceHiLoGenerator ,它无论如何都会应用HI / LO优化算法

But for Sequences, the actual identifier value is applied during flush-time , so you won't get the actual value until the session gets flushed (a manual flush or the commit-time flush). 但是对于序列,实际标识符值是在flush-time期间应用的,因此直到会话被刷新(手动刷新或提交时刷新)后,您才能获得实际值。

For IDENITY generator, you get the identifier generated prior to flushing, but that disables JDBC batching so it's not a silver-bullet either. 对于IDENITY生成器,您将获得在刷新之前生成的标识符,但这会禁用JDBC批处理,因此它也不是子弹头。

If you want full control, you need to resort to assigned identifiers and UUID surrogate keys are perfect for this job. 如果要完全控制,则需要使用分配的标识符,并且UUID代理键非常适合此工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM