gcrain
gcrain

Reputation: 602

how does hibernate generator increment handle deletes

This is how i am using the generator:

    <id name="id" column="column_name">
        <generator class="increment"/>
    </id>

private Integer id;

The behaviour that I am seeing is:

  1. create the first object
  2. hibernate assigns id = 1
  3. delete that object
  4. shut down the server and restart it (added this after the answer)
  5. create a second object
  6. hibernate assignes id = 1

note: I expected the new number to be 2, even though 1 doesnt exist anymore.

I have only tested this using HSQLDB.

Question: Is this expected behaviour?

AFAICT in the source, the next number should be 2 https://github.com/hibernate/hibernate-core/blob/master/hibernate-core/src/main/java/org/hibernate/id/IncrementGenerator.java#L68

Update: As per Ralph's answer, if I skip step 4 (dont shut down the server), it increments correctly. Its because the value gets set to max(id) on start up, and stored in memory after that.

Upvotes: 2

Views: 1010

Answers (1)

Ralph
Ralph

Reputation: 120781

The IncrementGenerator is initialized with "select max(" + column + ") from " + buf.toString(); where column is the ID column.

This means every time a new IncrementGenerator is created (more precise: the first time generate is invoked after configure is invoked) the id counter will be "reseted" to the max value from the DB.

Upvotes: 3

Related Questions