-2

I am getting an error when I try to run my Java spring boot application . Please find below the code snippets and the error I am getting.

setAdmin() method in Controller class

 @PutMapping("/update/{id}")
    //@PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<User> setAdmin(@PathVariable("id") Long id, @RequestBody User user) {
        Optional<User> userData = userRepository.findById(id);
        Optional<Role> adminRole = roleRepository.findByName(ERole.ROLE_ADMIN);
        Set<Role> roles = new HashSet<>();
        roles.add(adminRole.get());
        if (userData.isPresent()) {
            User _user = userData.get();
            _user.setRoles(roles);
            return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

RoleRepository interface

public interface RoleRepository extends JpaRepository<Role, Long> {
   Optional<Role> findByName(ERole name);

}

ERole enum

public enum ERole {
    ROLE_USER,
    ROLE_MODERATOR,
    ROLE_ADMIN
}

The error

erreur:
Cannot invoke "com.jwt.authentification.Repository.RoleRepository.findByName(com.jwt.authentification.Domaine.ERole)" because "this.roleRepository" is null
Kthree
  • 156
  • 1
  • 12
Riqqa
  • 11
  • 3

1 Answers1

-3

Most probably you have to instantiate the repository using the @Autowired annotation.

JohnSmith
  • 1
  • 1
  • thank you , it is ok but methode not work . without erreur – Riqqa May 04 '22 at 07:40
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 04 '22 at 21:13