I'm trying to get a list of models based on a custom string field. From the User class, I want to search the database and retrieve all models that contain a specific role
value.
Model class
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String role;
...
}
Repository class
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
List<User> findById(@Param(value = "id") Long id);
List<User> findByRole(@Param(value = "role") String role);
}
Service class
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public List<User> findUserById(@PathVariable("id") Long id){
return userRepository.findById(id);
}
public List<User> findUserByRole(String role){
return userRepository.findByRole(role);
}
...
}
Controller class
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
UserService userService;
@GetMapping
public List<User> accessUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public List<User> findById(@PathVariable("id") Long id){
return userService.findUserById(id);
}
@GetMapping("/{role}")
public List<User> findByRole(@RequestParam(value="role") String role){
return userService.findUserByRole(role);
}
...
}
I make the request as follows (where role=MANAGER):
GET localhost:8080/api/users/MANAGER
However, I get this error. I noticed that if I'm trying to get models based on a Long id value it works, but whenever I attempt to do it with a String field, it gives the error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Ambiguous handler methods mapped for '/api/users/CHEF': {public java.util.Optional com.cs322.ors.controller.UserController.accessUserInfo(long,org.springframework.security.core.Authentication), public java.util.List com.cs322.ors.controller.UserController.findByRole(java.lang.String)}
I tried the following links but the issue persists: