How to lock a transaction for reading a row and then inserting in Hibernate?

Posted by at on Stack Overflow See other posts from Stack Overflow or by at
Published on 2010-05-25T08:25:09Z Indexed on 2010/05/25 8:31 UTC
Read the original article Hit count: 157

Filed under:
|
|
|
|

I have a table with a name and a name_count. So when I insert a new record, I first check what the maximum name_count is for that name. I then insert the record with that maximum + 1. Works great... except with mysql 5.1 and hibernate 3.5, by default the reads don't respect transaction boundaries. 2 of these inserts for the same name could happen at the same time and end up with the same name_count, which completely screws my application!

Unfortunately, there are some specific situations where the above is actually fairly common. So what do I do? I assume I can do a pessimistic lock where any row I read is locked for further reading until I commit or roll-back my transaction. Or I can do an optimistic lock with a version column that automatically keeps trying until there are no conflicts?

What's the best approach for my situation and how do I specify it in Hibernate 3.5 and mysql 5.1? The above table is massive and accessed frequently.

© Stack Overflow or respective owner

Related posts about mysql

Related posts about hibernate