Hi.
i want to make my username field as unique.
so that if i repeats the username it will show an error like user already exists.
can any body help me regarding this.Thanks in advance:)
Printable View
Hi.
i want to make my username field as unique.
so that if i repeats the username it will show an error like user already exists.
can any body help me regarding this.Thanks in advance:)
I was planning on making a tutorial any way, so I just started with 0, should help you I think
http://hatimonline.com/2010/08/04/sp...ty-tutorial-0/
Thanks a lot...
But its showing an exception like..
org.hibernate.exception.ConstraintViolationExcepti on: could not insert: [com.unique.domain.SystemUser]; nested exception is javax.persistence.EntityExistsException: org.hibernate.exception.ConstraintViolationExcepti on: could not insert: [com.unique.domain.SystemUser]
means its taking the field as unique and generating the exception as and when i
want to enter duplicate value...
Kindly guide more....
Have you configured the validator?
My SystemUserController is like
public class SystemUserController {
@Autowired
private Validator systemUserValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(systemUserValidator);
}
}
and my SystemUserValidator is like
public class SystemUserValidator extends LocalValidatorFactoryBean implements Validator {
private static final Log logger = LogFactory.getLog(SystemUserValidator.class);
@Override
public boolean supports(Class<?> clazz) {
return SystemUser.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
super.validate(target, errors);
SystemUser user = (SystemUser) target;
if (user != null) {
if( SystemUser.findSystemUsersByUsername(user.getUsern ame()).getResultList().size() > 0 )
errors.rejectValue("username", "The username '"+user.getUsername()+"' is already in use", "The username '"+user.getUsername()+"' is already in use");
}
else {
errors.reject("SystemUser object not available");
}
}
suggest more
Ah thanks for pointing out, there is an important piece missing in my blog (should have shared the code)
It needs a @Component annotation on top for component scanning to work (the annotation is for the entire Validator class)
Otherwise auto wired wont work.
Hey it works fine now...
Thank u very much..