简体   繁体   中英

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. 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') ?

Thanks

Using the JPA @SequenceGenerator along with the legacy Hibernate identifiers will give you the SequenceHiLoGenerator that applies a HI/LO optimization algorithm anyway.

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).

For IDENITY generator, you get the identifier generated prior to flushing, but that disables JDBC batching so it's not a silver-bullet either.

If you want full control, you need to resort to assigned identifiers and UUID surrogate keys are perfect for this job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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