4

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

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
AndreDuarte
  • 784
  • 1
  • 5
  • 21
  • Did you try session.persist() ? persist will put the object into session but does not save it into the db yet, so, there could be a good chance that it will generate the sequence for you. – Zeus Dec 15 '14 at 17:46
  • 2
    I'll take back my answer.. persist does not give you generated id immediately http://stackoverflow.com/a/5862722/258741 – Zeus Dec 15 '14 at 17:48

1 Answers1

7

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911