-
Aug 2nd, 2010, 05:10 AM
#1
How to make a field unique with userdefined Exception
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
-
Aug 3rd, 2010, 07:44 PM
#2
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/
-
Aug 4th, 2010, 02:34 AM
#3
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....
-
Aug 4th, 2010, 04:21 AM
#4
Have you configured the validator?
-
Aug 4th, 2010, 06:47 AM
#5
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
-
Aug 4th, 2010, 08:24 AM
#6
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.
-
Aug 6th, 2010, 06:15 AM
#7
Hey it works fine now...
Thank u very much..
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules