How to @Validate unique username in spring?

后端 未结 3 1132

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:04

    JSR-303 does not support what you want (something like a @Unique constraint). You have to write you own validator. How can this be done is explained here: https://community.jboss.org/wiki/AccessingtheHibernateSessionwithinaConstraintValidator

    But before doing that make sure you read this answer: https://stackoverflow.com/a/3499111/1981720

    And this sentence from the previous article:

    The reason @Unique is not part of the built-in constraints is the fact that accessing the Session/EntityManager during a valiation is opening yourself up for potenital phantom reads.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 23:25

    You can use UserDetailsService prepared spring class and extend it and customize it :

    @Service
    public class LoginDetailsServiceImpl implements UserDetailsService, Serializable {
    
        @Autowired
        LoginService loginService;
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            if (username == "" || username.isEmpty()) {
                throw new UsernameNotFoundException(String.format("User %s is invalid!", username));
            }
            Login login = loginService.find(username);
            if (login == null) {
                throw new UsernameNotFoundException(String.format("User %s does not exist!", username));
            }
            if (!loginService.scheduleChecking(login.getScheduled())) {
                throw new UsernameNotFoundException(String.format("User %s is not authorized this time!", username));
            }
          //....
    
    0 讨论(0)
提交回复
热议问题