Spring Boot按名称查询英雄接口报错:类型转换失败求助
问题排查与解决
核心错误原因
- 请求路由匹配错误:
HeroesRepository添加了@RepositoryRestResource注解,Spring会自动生成默认REST接口,其中包含/api/heroes/{id}的查询接口。当你发起http://localhost:8080/api/heroes/buscar?name=Pisicola请求时,Spring将buscar识别为该默认接口的id参数,而id是Long类型,无法将字符串buscar转换为Long,因此抛出转换错误。 - 接口注解与请求方式不匹配:你定义的接口使用了
@GetMapping("/buscar/{name}")(路径变量模式),但实际请求采用的是查询参数?name=xxx的方式,两者不对应。
具体修复方案
方案一:适配查询参数请求(匹配你的现有请求方式)
修改控制器中的查询接口,移除路径变量配置,保留查询参数的注解:
@GetMapping("/buscar") public ResponseEntity<List<Heroe>> findHeroByName(@RequestParam String name) { List<Heroe> heroes = heroesRepository.findByName(name); return new ResponseEntity<>(heroes, HttpStatus.OK); }
修改后,你的原请求http://localhost:8080/api/heroes/buscar?name=Pisicola即可正常返回结果。
方案二:适配路径变量模式(匹配原接口定义)
如果希望保留路径变量的接口设计,将请求改为:
http://localhost:8080/api/heroes/buscar/Pisicola
同时修正接口的参数注解为@PathVariable:
@GetMapping("/buscar/{name}") public ResponseEntity<List<Heroe>> findHeroByName(@PathVariable String name) { List<Heroe> heroes = heroesRepository.findByName(name); return new ResponseEntity<>(heroes, HttpStatus.OK); }
额外优化:完善控制器其他接口的注解
你的控制器中getHeroeById、updateHeroe、deleteHeroe方法缺少对应的请求注解,导致这些接口无法被正常访问,建议补充完整:
@GetMapping("/{id}") public ResponseEntity<Heroe> getHeroeById(@PathVariable long id) { Heroe heroe = heroesRepository.findById(id).orElseThrow(); return new ResponseEntity<>(heroe, HttpStatus.OK); } @PutMapping("/{id}") public ResponseEntity<Heroe> updateHeroe(@PathVariable long id, @RequestBody Heroe heroe) { // 先校验英雄是否存在,再执行更新逻辑 Heroe existingHeroe = heroesRepository.findById(id).orElseThrow(); existingHeroe.setName(heroe.getName()); // 补充其他字段的更新逻辑 Heroe updatedHeroe = heroesRepository.save(existingHeroe); return new ResponseEntity<>(updatedHeroe, HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteHeroe(@PathVariable long id) { heroesRepository.deleteById(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
补充说明
如果不需要Spring Data REST自动生成的默认接口,可以直接移除HeroesRepository上的@RepositoryRestResource注解,仅保留自定义控制器中的接口即可。
内容的提问来源于stack exchange,提问作者Dox
相关产品推荐
相关产品推荐

