How to ensure that only the row table is created with a specific state?
I have a domain object that looks something like this:
class UserStuff
{
String userid;
boolean primordial;
}
In the table, the primordial is TINYINT. A user can have as many UserStuffs as possible . I want to ensure that only one row (the first row is created) will have the original == 1. All subsequent rows will have the desired == 0. At first glance, there is nothing to worry about. Assuming multiple create requests for UserStuff can occur at the same time, how can I guarantee this limitation?
My initial idea is to sync a string (in a domain service)
class DomainService
{
public void create( UserStuff stuff )
{
synchronized( stuff.userid + "/userstuff/lock" )
{
...
}
}
}
I would love to hear comments about this and alternative methods. Thanks to
a source to share
The SQL approach, generally speaking, is to make a (userid, primordial)
unique composite key and use a statement INSERT
with a clause ON DUPLICATE KEY UPDATE
- which sets primordial
otherwise (but I admit I don't know what happens if it UPDATE
also ends up in a duplicate, like if you entered second non-primordial UserStuff
).
Alternatively, with suitable isolated transactions, you can first SELECT
check that this one is userid
already present and then within the same transaction INSERT
with the corresponding values primordial
.
The SQL approach would be more robust if you had updates from multiple processes (possibly on different client nodes), but perhaps if you are 100% sure it will never happen, your ideas based on Java simulation. can get better performance ... I won't guess one way or another, but recommend you measure things both ways (if you're willing to put your shirt on never, never get updates from multiple client nodes, that is; -.)
`
a source to share