Announcement Announcement Module
No announcement yet.
How to make a field unique with userdefined Exception Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to make a field unique with userdefined Exception

    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

  • #2
    I was planning on making a tutorial any way, so I just started with 0, should help you I think


    • #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....


      • #4
        Have you configured the validator?


        • #5
          My SystemUserController is like

          public class SystemUserController {

          private Validator systemUserValidator;


          protected void initBinder(WebDataBinder binder) {



          and my SystemUserValidator is like

          public class SystemUserValidator extends LocalValidatorFactoryBean implements Validator {

          private static final Log logger = LogFactory.getLog(SystemUserValidator.class);

          public boolean supports(Class<?> clazz) {
          return SystemUser.class.isAssignableFrom(clazz);

          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


          • #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.


            • #7
              Hey it works fine now...
              Thank u very much..