简体   繁体   中英

Hibernate Save method with SQL Server Identity column

We are using Hibernate Save method to insert data in a SQL Server table which has an identity column.

@GeneratedValue(strategy=GenerationType.AUTO) 

annotation is used and we are able to insert the data and identity column is getting incremented as well.

The issue is: If for any reason insertion in table fails then also identity column's value is incremented. Consequently the next successful insertion takes +2 value. eg First successful insertion resulted in Identity column value as 1.
Second insertion got failed.
Third successful insertion resulted in identity column value as 3 instead of 2.

This seems to be a common problem as Hibernate save method returns the generated id immediately. Please suggest an optimal alternate solution so that identity column value does not gets incremented on failures.

As per the best of my knowledge, the only solution to this problem is that you have to assign an ID to the object via your application explicitly instead of letting hibernate or database generate it for you.

In order to do this,

  1. In annotation based approach, just remove @GeneratedValue annotation, instead use only @Id .
  2. In mapping file based approach, specify assign as the generator class, eg <generator class="assigned"> .

Now :

  1. Create your own algorithm to generate unique primary keys.
  2. Make a Primary Key an int or long and not serial .
  3. Get a number from the algorithm.
  4. Use it as an ID for your object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM