I want to sort items by ID and by "Role" like that:
- http://localhost:8080/employees --> All items, it works!
- http://localhost:8080/employees/1 --> by ID(long), it works!
- http://localhost:8080/employees/BURGLAR --> by "Role"(String from ENUM "RoleList"), doesn't work...
Spring thinks that i want to refer to the Long type of ID when I'm referring to "Roles" and colapses logically. I tried a few options related to similar errors but none works for me... Here is the code:
//My repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { Optional<Employee> findById(Long id); List<Employee> findByRole(RoleList role); } public class Employee { private @Id @GeneratedValue Long id; private String name; private RoleList role; Employee() { } public Employee(String name, RoleList role) { this.name = name; this.role = role; } //Getter and setters............. @Override public String toString() { return "Employee [id = " + getId() + ", name = " + getName() + ", role = " + getRole().getNameRole() + ", with salary of = " + getRole().getSalaryRole() + "]"; } } public enum RoleList { BURGLAR("burglar", 1500), THIEF("thief", 2000), MAGE("mage", 3500); private String role; private int salaryRole; private RoleList(String role, int salaryRole) { this.role = role; this.salaryRole = salaryRole; } public int getSalaryRole() { return salaryRole; } public String getNameRole() { return role; } //initial database class LoadDatabase { @Bean CommandLineRunner initDatabase(EmployeeRepository repository) { return args -> { log.info("Preloading " + repository.save(new Employee("Bilbo Baggins", RoleList.BURGLAR))); log.info("Preloading " + repository.save(new Employee("Frodo Baggins", RoleList.THIEF))); log.info("Preloading " + repository.save(new Employee("Gandalf the Grey", RoleList.MAGE))); }; } } // Single item by id @GetMapping("/employees/{id}") Employee one(@PathVariable Long id) { return repository.findById(id).orElseThrow(() -> new EmployeeNotFoundException(id)); } //... This works as expected... Then I have few options, none of this works...
// Items by role @GetMapping("employees/role/{role}") List<Employee> getRoles(@PathVariable (value="role")String role) { List<Employee> listRolesEmployees = repository.findByRole(RoleList.valueOf(role)); return listRolesEmployees; } //...or...
@RequestMapping(value = "employee/{role}", method = RequestMethod.GET) List<Employee> getRoles(@PathVariable String role) { List<Employee> listRolesEmployees = repository.findByRole(RoleList.valueOf(role)); return listRolesEmployees; } //...or...
@RequestMapping(method = RequestMethod.GET) public List<Employee> getRoles(@RequestParam(value="role") String role) { List<Employee> listRolesEmployees = repository.findByRole(RoleList.valueOf(role)); return listRolesEmployees; } Sorry for my english and thanks!
@PathVariable RoleList roleor even@PathVariable("id") Employee employee.