Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Since I am new to this framework i am not getting proper examples, can anyone tell me how to avoid duplicate username insertion in to DB? I just selected the username from the DB and put it into the List, now I just want to validate it for duplicate insertion and throw a message if there is already a name exists in DB.

ArrayList namelist = new ArrayList();
String name1 = "select P.name from Person P;
Query q1 = em.createQuery(name1);
namelist.addAll(q1.getResultList());
share|improve this question
3  
Create a unique index on the column and catch the exception in the Java code –  a_horse_with_no_name May 30 at 7:38

2 Answers 2

Simply put a unique index on the username column, and handle the "is a duplicate" exception gracefully.

share|improve this answer

I would use an AbstractFormValidator and avoid exception handling since to me this is not an exceptional situation but something that i know can happen. Below is some sample code. In the validate method i look in the DB if there is already an user with the requested username and if yes output an error.

public class UsernameValidator extends AbstractFormValidator {

    private FormComponent[] componentsToValidate;

    private SomeUserService someUserService;

    public UsernameValidator(FormComponent userNameField) {
        componentsToValidate = new FormComponent[]{userNameField};
    }

    @Override
    public FormComponent<?>[] getDependentFormComponents() {
        return componentsToValidate;
    }

    @Override
    public void validate(Form<?> form) {
        final String userNameToCheck = componentsToValidate[0].getInput();
        if (someUserService.getUserByLogin(userNameToCheck) != null) {
            error(componentsToValidate[0]);
        }
    }

}
share|improve this answer
1  
There's still a race condition here - so even if you do this you must still handle a unique violation exception that's thrown if somebody creates the user between when you check if it exists and when you create it. You could for a low traffic table like this probably LOCK TABLE ... IN EXCLUSIVE MODE (blocking concurrent writes, but permitting reads) to avoid that though. –  Craig Ringer May 31 at 2:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.