0

Assuming I have a simple hibernate entity like so

@Entity
public class SomeEntity {
    @Id
    private long id;

    // Other fields...
}

I want to generate sequence for the id column with consideration of any deleted entities. Meaning I don't want the sequence to be incremented for every new entity saved to the database, but to reuse values assigned to entities that were deleted. For example in the db I have these entities saved

|---------------------|
|          ID         |
|---------------------|
|          1          |
|---------------------|
|          2          |
|---------------------|

So the next entity id should get the value 3. But in case the entity with id '1' was deleted, the next time I save an entity to the database I want its id to be '1'

How can this behaviour can be implemented using Hibernate?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 3
    Could you explain why do you need it? – SternK Aug 25 '20 at 07:47
  • I guess that this question should be rather addressed to the underlying database. See for example [this](https://stackoverflow.com/questions/9984196/postgresql-gapless-sequences) question – SternK Aug 25 '20 at 07:54
  • 3
    Does this answer your question? [JPA, Reuse of deleted ID](https://stackoverflow.com/questions/18031469/jpa-reuse-of-deleted-id) Or this? [hibernate @GeneratedValue , how to deal with deleted rows. in mysql](https://stackoverflow.com/questions/26651754/hibernate-generatedvalue-how-to-deal-with-deleted-rows-in-mysql) – Nowhere Man Aug 25 '20 at 07:56

1 Answers1

0

In the end, a DB sequence doesn't work that way. You will have to implement a DB query to get the minimum available ID and set the entity ID manually.

JLazar0
  • 1,257
  • 1
  • 11
  • 22