I have a question about concurrency and databases. And maybe hibernate has a solution for this.
I've built a concurrent system which reads a record from one db transforms it and saves it to another db.
This is done with the command pattern, where each entity is contained within a command.
The command copies all properties from the source entity and saves it in the properties of the target entity which is then persisted. should a property contains a reference to another entity, the owning command will fire a command that handles this referenced entity, this will cascade until the end of the tree branch.
The problem is this.
Concurrency.
Imagine an Order entity which has a property called State. The OrderCommand will copy all properties fine and when it comes to the state property it will fire the StateCommand, which will copy the state properties.
Now comes the problem. In a concurrent environment, commands are persisting the state property simultaniously. The id's are all assigned. a lot of Order records has the same state. Even though i've built a mechanism, where it will check the db for record existence, when run concurrently this check on db is not enough. because when i do a findByID on StateCommand before persisting, this record might not exist, thus giving a green light for saving it in the db, meanwhile, another thread has persisted this, resulting in a primary key constraint error and a major headache.
Is there any way i can do the check on hibernate level instead of on the db level? checking on db is not atomic enough and causes race conditions. Can I do something like, session.get before persisting instead of doing findByID on the db?
any help is appreciated, thanks
Max
|