Dealing with concurrency issues at the database level
How would you go about dealing with multiple users accessing a database record concurrently, specifically if you have an instrument reservation table and you wish to prevent two users reserving the same instrument if they were to try reserving it at exactly the same time, I thought that setting the isolation level to serializable should do it, but as it turns out isolation level doesn’t do that, so how would you detect concurrent accesses to the entry and rollback any changes? I am using JDBC with MYSQL server, 开发者_StackOverflowand InnoDB engine.
thanks
I would lock the row explicitly using:
START TRANSACTION
SELECT ... FROM mytable WHERE id=? FOR UDPATE
...
COMMIT TRANSACTION
Between the "select for update", and the commit, no other session will be able to do a "select for update" on that row. (But other sessions will be able to read the row in its old state if not preceded by a "select for update", and other sessions will be able to write and "select for update" other rows and other tables.)
精彩评论