[英]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, 为此,
@GeneratedValue
annotation, instead use only @Id
. @GeneratedValue
注释,而仅使用@Id
。 assign
as the generator class, eg <generator class="assigned">
. assign
为生成器类,例如<generator class="assigned">
。 Now : 现在:
int
or long
and not serial
. int
或long
而不是serial
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.