8

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

Androider
  • 2,884
  • 5
  • 28
  • 47

3 Answers3

10

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.

Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82
5

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

Community
  • 1
  • 1
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
0

The main reason this is not supported internally is security. let me give you an example,

1. Security

We have a database for mobile SimCards which has unique identification number. If your sim is lost and then you de-activated it. But lets say some other user bought a new sim and that sim given the old unique number which your sim had(by your logic). Then it might lead to a problem. Like lets say that new user done some terrorist act, then police gonna track that sim number and might come to you.(as he was new user and some at places sim still shows your name only) ...

2. latency

And definitely the performance issue is there. Each search to find unused sequence number will be O(n) instead of straight forward O(1) .

Community
  • 1
  • 1
Amol Maid
  • 23
  • 6