Assigned Key and Insert in Hibernate in a single Transaction
I'm using Spring with Hibernate (and SQL Server database). For one of my entity I need to generate the PK that is a combination of a number and string..something like ABC1001, DEF1002 etc..
I'm using 'assigned
' key for my entities since this kind of PK (combination of a number and string, i.e. ABC 1001) cannot be generated through a plain sequence/identity.
What I want is to
- Generate the PK through an DB Identity and increase the Identity value by 1 (for next PK generation)
- Combine the outcome (i.e. number returned by previous step) with appropriate String (i.e. ABC) to make it a PK for my Entity for ex: ABC1001
- Assign this key to my entity and persist my data by calling session.save()
If anything fails, rollback the transaction, i.e. rollback entity insert and rollback any changes made to Identity
An approach that I've in mind is to: Create a Stored Procedure that can perform the first two step (Generate PK, Increment Identity, Combine the number with String) and then assign the key to Entity and call session.开发者_如何学编程save().
My problem is that I'll have to use HibernateCallBack to execute my Procedure where I'll have to deal with JDBC Connection. Once the method finishes, i'll have to close the JDBC connection, and then in next step I can proceed with saving my entity (session.save()
).
I'm not finding a way to execute the two things [i.e. calling the procedure and calling session.save()] in a single transaction. I'm using declarative transaction offered by Spring.
Is there a way to execute the two things in a single transaction, so if entity insert fails, I can even rollback the changes made to Identity?
Or is there any better strategy you can suggest?
精彩评论