Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 582
AndreDuarte Avatar asked Sep 06 '25 03:09

AndreDuarte


1 Answers

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.

like image 140
Vlad Mihalcea Avatar answered Sep 07 '25 23:09

Vlad Mihalcea