AndreDuarte
AndreDuarte

Reputation: 804

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

Upvotes: 4

Views: 6016

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153780

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.

Upvotes: 7

Related Questions