Hi,
I'm trying to figure out how I can solve the following problem. Here is the situation. I have 2 entities: delivery and user. The relationship between these entities is many to one: multiple deliveries for one user. When the application persist a delivery, the associated user is either created or the existing one is referenced via a retrieval since users must be unique.
Everything works fine up to this point. The problem is that when there are multiple concurrent Hibernate sessions, it happens that they try to persist the same user. The cause of the problem is that when each process verify the presence of the user, they don't find it so they try to persist it but when the transactions commit, one or more of them fail with a duplicate key constraint violation because the user has already been persisted by another process.
The problem exists since I use optimistic locking with read commited isolation level to handle concurrency.
The solution I can imagine is when a duplicate key error occurs then I could wait a very short delay and retry the whole operation. During the retry, the existing user would be detected and thus referenced in the delivery.
While this solution should work, I don't really like it because it requires some retry logic development in the persistence layer. I'm wondering if I could specify some instructions in the Hibernate mappings to automate this retry logic?
I use Hibernate 3.1.3 with the Spring's JDBC framework on top of it. The application runs on Linux Redhat enterprise with Java 5.
Thank you for your help in advance.
|