Hibernate version: 2.0
Suppose I have an entity called 'Account' with a primary key field 'username'. Now, a user wants to create an 'Account' so they submit their preferred username, say "Fred".
How do I check if "Fred" exists, and if it doesn't, insert (Session.save) the Account?
For example, consider the following code:
Code:
tx = session.beginTransaction();
if(session.get(Account.class, "Fred") != null)
{
tx.commit();
// tell the user that this account username already exists
}
else
{
Account a = new Account();
session.save(a, "Fred");
tx.commit();
}
I'm not sure how close this is to being correct, but I know that if two concurrent users are executing this code, there is potential for a race condition. If "Fred" doesn't exist, then user1 executes up to the point where the Account instance is created, then user2 executes, who also gets into the 'else block' - one of them will fail with a primary key violation.
So the question is, how do I achieve what I want to achieve - that is check if the account exists and if it doesn't, create that account; all in one atomic operation?