Hi all,
I'm writing a desktop application which uses MySQL database as a data storage. In the application I have documents which are loaded from the database, edited in the client and then saved back to the database.
Now I'd like to implement a same kind of like functionality that for example Word offers when two users try to open the same document at the same time. I mean, first guy, who opens the document, gets read-write access to it and all openings after that lead to read-only versions of the document.
I'm using versioning to give me long transactions for the UI tier, but I don't like the default schema they offer me (the guy, who saves first, succeeds) so I planned to implement this kind of locking by creating DocumentLock persistent object.
When user opens some document, the search is conducted to DocumentLock objects and if there is already existing lock object for opened document, the document is opened read-only (= one boolean property in the Document object is set to true). If there is no such an object, a new lock object is created, persisted to the database and the document is opened read-write.
My problem is that I haven't been able to create a proper strategy for searching and creating lock objects in an atomic way. Either I end up having two read-write documents open or get BatchUpdateException from DB saying that a deadlock has occurred. Using common sense I think that this kind of schema should be implementable without a fear of deadlocks in this way:
Code:
Client 1 Client 2
| |
begin tx |
| |
select ... for update |
(looks if there is already |
a lock) |
| begin tx
| |
| select ... for update
| (starts also looking,
| is blocked)
| |
insert into lock ... (still blocked)
(insert a new lock) |
| |
select ... |
(loads document |
read/write) |
| |
| |
commit |
| |
| (unblocks)
| (gets the new lock
| among the results ->
| opens read-only)
How could I implement this kind of transaction schema using Hibernate?
Or is there some better way to implement this kind of "long transaction" locking?
Sincerely,
Jouni Hartikainen