我想按 ID 和“角色”对项目进行排序:
- http://localhost:8080/employees --> 所有项目,都有效!
- http://localhost:8080/employees/1 --> 通过 ID(长),它有效!
- http://localhost:8080/employees/BURGLAR --> 通过“Role”(来自 ENUM“RoleList”的字符串),不起作用...
当我引用“角色”时,Spring 认为我想引用 Long 类型的 ID,并在逻辑上崩溃。我尝试了一些与类似错误相关的选项,但没有一个对我有用...这是代码:
//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));
}
//...这按预期工作...然后我几乎没有选择,这些都不起作用...
// 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;
}
//...或者...
@RequestMapping(value = "employee/{role}", method = RequestMethod.GET)
List<Employee> getRoles(@PathVariable String role) {
List<Employee> listRolesEmployees = repository.findByRole(RoleList.valueOf(role));
return listRolesEmployees;
}
//...或者...
@RequestMapping(method = RequestMethod.GET)
public List<Employee> getRoles(@RequestParam(value="role") String role) {
List<Employee> listRolesEmployees = repository.findByRole(RoleList.valueOf(role));
return listRolesEmployees;
}
抱歉我的英语不好,谢谢!
最佳答案
在您的端点中,您使用:
@RequestMapping(value = "employee/{role}", method = RequestMethod.GET)
但是在请求中http://localhost:8080/employees/BURGLAR
这不是同一个路径(额外的字符s
)。
你陷入了错误的终点:
@GetMapping("/employees/{id}")
Employee one(@PathVariable Long id) {
但是BURGLAR
不是Long
。
这会导致转换错误。
关于java - 无法在 SPRING 中将类型 'java.lang.String' 的值转换为所需类型 'java.lang.Long',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60327296/