Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID before saving to database

I use hibernate sequences to generate id of an entity. I use PostgreSQL 9.1.

Is it possible to get entity id before it is saved to database? How?

like image 297
VB_ Avatar asked Dec 20 '13 11:12

VB_


2 Answers

You explicitely create a separate sequence, get its value, then insert an object with id based on that value. You will have more code, but the ID will be available before the insertion and the guarantees for sequences are exactly the same as for serially given IDs, because they are essentially the same.

In other words:

  • create your own sequence
  • make a primary key a simple int not serial
  • get a number from sequence
  • use it as an ID for your object

This question has an answer saying how to get next sequence value.

like image 151
Dariusz Avatar answered Sep 28 '22 09:09

Dariusz


save() method returns the id of the entity that is saved. You can use it!

reference:-> http://docs.jboss.org/hibernate/annotations/3.5/api/org/hibernate/Session.html

like image 33
Vijay Avatar answered Sep 28 '22 09:09

Vijay