3

索引上有一个 UNIQUE 数据库约束,它不允许多个记录具有相同的列。

有一段代码,由 Hibernate (v2.1.8) 管理,执行两次 DAO
getHibernateTemplate().save( theObject )
调用,结果将两条记录输入到上面提到的表中。

如果此代码在没有事务的情况下执行,则会产生 INSERT、UPDATE,然后是另一个 INSERT 和另一个 UPDATE SQL 语句,并且工作正常。显然,顺序是先插入包含 DB NULL 的记录,然后用适当的数据更新它。

如果此代码在包装在单个 Spring 事务中的 Spring (v2.0.5) 下执行,则会导致两个 INSERTS,然后由于上述 UNIQUE 约束而立即出现异常。

由于与 ANSI SQL 不兼容,此问题仅在MS SQL上表现出来。它在 MySQL 和 Oracle 上运行良好。不幸的是,我们的解决方案是跨平台的,必须支持所有数据库。

拥有这些技术堆栈,对于给定问题,您首选的解决方法是什么?

4

2 回答 2

1

您可以尝试在两次保存之间刷新休眠会话。这可能会强制 Hibernate 在第二次插入之前执行第一次更新。

另外,当你说hibernate用插入插入NULL时,你的意思是每一列都是NULL,还是只是ID列?

于 2008-09-28T12:22:53.983 回答
0

I have no experience in Hibernate, so I don't know if you are free to change the DB at your will or if Hibernate requires a specific DB structure you cannot change.

If you can make changes then you can use this workaround in MSSQL tu emulate the ANSI behaviour :

drop the unique index/constraint

define a calc field like this:

alter table MyTable Add MyCalcField as 
case when MyUniqueField is NULL 
      then cast(Myprimarykey as MyUniqueFieldType) 
      else MyUniqueField end

add the unique constraint on this new field you created.

Naturally this applies if MyUniqueField is not the primary key! :)

You can find more details in this article at databasejournal.com

于 2008-09-26T07:53:15.187 回答