In my web application (java+mySQL) I have the following server side (pseudo)code:
select count(*) c form table where condition;
if c>0 then update...
else insert...
In some situations (heavy load, multiple click, slow connections) it seems that different requests execute the select at once, generating thus multiple records instead of only one.
I’m looking for the best and safest way to avoid this.
It will be enough to put the whole block in a transaction, and which level, serializable?
Should I be careful with locking conditions, considering that other parts of the application could write/read on the same table for other reasons?
Other solutions?
PS.
INSERT … ON DUPLICATE KEY UPDATE is not an option as I don’t have an usable unique key.