I created a custom validation rule to check if a username exists in the database.
My User class has a username that has a custom validation rule that when an object is created it checks in the database if that same username exists.
I use an interface UserRepository extends JpaRepository<User, Integer>
to save the users to the database and in the custom validation rule to check if the username already exists. I make use of
@Autowired
UserRepository userRepository;
Separately I can validate users and save them to the database, but when using them together like calling userRepository.save(user);
the @Autowired UserRepository userRepository;
in the custom validation rule does not get initiated so it remains null.
javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
Custom validation rule
public class UsernameConstraintValidator implements ConstraintValidator<Username, String> {
@Autowired
UserRepository userRepository;
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return !userRepository.existsUserByUsername(s);
}
}
Trying to save user in the controller
@PostMapping("/save")
public String save(@Valid @ModelAttribute("user") User user,BindingResult result, @RequestParam String password2){
if(result.hasErrors()) return "register";
userRepository.save(user);
return "login";
}
Here is the full stack trace: https://justpaste.it/7rnx7
Here is the full project: https://github.com/leotrimvojvoda/todo