How to @Validate unique username in spring?

后端 未结 3 1131

Let\'s assume that I have a form where I might submit username(@NaturalId) and password for a new user.

I would like to add the user with a

3条回答
  •  礼貌的吻别
    2021-01-07 23:15

    AFAIK there isn't an annotation to do this. You have two options

    One, create a custom validator annotation. Here is a very good example. Make a call to your DAO class and check the availability in the validator implementation

        public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
    
        return userDAO.userNameAvailable(object); //some method to check username availability
        }
    

    OR

    Set unique = true on your property in your entity class.

        @Column(unique = true)
        private String userName;
    

    But this will not work with @valid, instead throw an exception on persistence. You have to use an appropriate logic to handle that.

    The first solution isn't fool proof. Check this answer on SO.

    The second will will never fail.

    UPDATE

    As NimChimpsky commented, using both together will be a concrete solution.

提交回复
热议问题