PDA

View Full Version : creating a new object with safe care


shadowek
Aug 13th, 2004, 05:05 PM
Hi guys,
My DAO has the following methods:
boolean isAccountExist(Account account);//check if specified account exist in database
void createAccount(Account account); //save the specified Account object via saveOrUpdate
In the service layer I would like to have method creating a new account but only when the account doesn't exist yet; something like that:

public void createAccountService(Account account)
{
if(!dao.isAccountExist(account))
{
//***1***
//other user can create the same account(with the same login name)
dao.createAccount(account);
}
}

The question is:how can I guarantee that between checking if account exist and creating the account in database (the ***1*** line in the above code snippet), no one create the same account (with the same login name)? I know that I must use transaction, but could you explicite show me how to configure it, please?

Colin Sampaleanu
Aug 13th, 2004, 05:28 PM
Your service layer should be already wrapped transactionally, first of all.

My strategy in the past has been to have the service layer code do a programatic check (via a query) for a duplicate existing username, email, etc.. This throws a checked exception, from which the ui can reover by letting the user type another value, and the service code can throw a different checked exception for each value which is being checked for dupes. Now of course, it is still possible that by the time you commit, anothr thread has inserted a record which would conflict. At that point, I am going to get a DataIntegrityViolationException. I consider this such a rare and unlikely case that I just let this go up as-is to the view layer, to be handled by a general RuntimeException handler there. Depending on the actual usage scenario of the app in question, this may not be a good enough strategy. The service layer could certainly just try to do a commit and catch the DataIntegrityViolationException itself, and then throwing a more specific checked exception.

Regards,

irbouho
Aug 13th, 2004, 05:36 PM
Just a small addition,

You need to create a unique index on your column (login name) to ensure the DataIntegrityViolationException will be thrown!!!

I also use the same strategy as Colin, this way, you can create new objects using a single round-trip to your database, and let your rdbms check if the record already exist.