A Hibernate native id generator doesn't work with a Microsoft SQL Server table that has a trigger that inserts a row into another table with an IDENTITY column. After Hibernate inserts a row, it executes 'select @@identity' to obtain the new row's identifier. This usually works. But if the insertion causes a trigger to insert a row into some other table that has an IDENTITY column, then 'select @@identity' returns the identifier of the latter row (that is the most recently generated identity), not what Hibernate expects. Havoc ensues.
This is a problem, for me. (I'm trying to apply Hibernate to a legacy database that matches this pattern.) Can you recommend a solution?
For example, here's a Hibernate mapping:
Code:
<class name="com.docent.lms.entities.reference.ReferenceUser" table="DRUser">
<jcs-cache usage="read-write"/>
<id name="id" type="long" column="userId" unsaved-value="null">
<generator class="native"/>
</id>
...
And here's some Transact-SQL to construct a problematic database:
Code:
CREATE TABLE DRUser(
userID int IDENTITY(1,1),
...
CREATE TABLE DRUserAuditTrail(
ID int IDENTITY(1,1),
userID int NOT NULL,
...
CREATE TRIGGER TI_DRUser_Audit ON DRUser
FOR INSERT
AS
SET NOCOUNT ON
INSERT INTO DRUserAuditTrail (userID, fieldID, operation, lastChange, perpID, eventDate)
SELECT INS.userID, ATF.ID, 'C', 'Y', ATU.perpID, ATU.eventDate
FROM ...
I'm using Hibernate 2.0.2 and SQL Server 2000 8.00.760.