简体   繁体   English

使用SQL Server标识列的休眠保存方法

[英]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. 我们正在使用Hibernate Save方法在具有标识列的SQL Server表中插入数据。

@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. 因此,下一次成功插入的值为+2。 eg First successful insertion resulted in Identity column value as 1. 例如,第一次成功插入会导致Identity列值为1。
Second insertion got failed. 第二次插入失败。
Third successful insertion resulted in identity column value as 3 instead of 2. 第三次成功插入导致标识列的值为3而不是2。

This seems to be a common problem as Hibernate save method returns the generated id immediately. 这似乎是一个常见问题,因为Hibernate save方法会立即返回生成的ID。 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. 据我所知,解决此问题的唯一方法是您必须通过应用程序显式地为对象分配ID,而不是让休眠或数据库为您生成ID。

In order to do this, 为此,

  1. In annotation based approach, just remove @GeneratedValue annotation, instead use only @Id . 在基于注释的方法中,只需删除@GeneratedValue注释,而仅使用@Id
  2. In mapping file based approach, specify assign as the generator class, eg <generator class="assigned"> . 在基于映射文件的方法中,将assign为生成器类,例如<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 . 将主键设置为intlong而不是serial
  3. Get a number from the algorithm. 从算法中获取一个数字。
  4. Use it as an ID for your object. 使用它作为对象的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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