Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Generated Value strategy

I am using this code in hibernate.

@Id @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="RightID", unique=true, nullable=false)

The problem is when i delete a row the 'RightId' don't remain in sequence. I want something like, hibernates should check id, if some id value is missing it must give that value to 'RightsId' otherwise proceed normally

like image 588
Androider Avatar asked Jun 01 '12 17:06

Androider


2 Answers

I don't think there is any such optio available in hibernate. Instead of AUTO,you can try the following strategy options also:

  1. GenerationType.TABLE - the persistence provider uses a database table for managing keys.

  2. GenerationType.SEQUENCE - the persistence provider uses a databases sequence for key generation. The database must support Sequences

  3. GenerationType.IDENTITY - the persistence provider defers to the database for key generation. The database must support the IDENTITY column type.

Another point : They may have not provide such option because it will slow down the performance also. For each insert, it will have to search through whole ID column. You can imagine how much it will impact to performace.

like image 54
Priyank Doshi Avatar answered Oct 16 '22 09:10

Priyank Doshi


Database do not care if there is holes in the sequence. Also in general it is possible and most likely easier to change application design so that it does not expect list of id values to not contain holes.

If some odd reason forces such a design, you have to use custom generator. Implementation details can be found via this question: Hibernate ID Generator

like image 5
Mikko Maunu Avatar answered Oct 16 '22 08:10

Mikko Maunu