Spring Boot基于JPA Repository实现动物GET查询接口问题求助
问题排查
以下是你现有代码存在的核心问题:
- 物种查询接口逻辑错误:你先调用
repository.findAll()获取全量数据赋值给列表p,后续的forEach(p::contains)只是判断元素是否存在,不会往p里添加元素,完全无法实现筛选需求。 - Repository方法定义错误:
findByspecie方法名不符合JPA驼峰命名规则,且返回值为Optional<Animal>只能返回单条数据,不符合同一物种返回多条的需求。 - 字段匹配错误:你代码里调用的
findByTitleContaining方法不存在,且你要匹配的是物种字段species,不是不存在的title字段。 - 冗余判断:路径变量
species是接口路径的必填部分,只要接口能接收到请求,该参数不可能为null,空判断完全多余。 - 可选优化点:前两个接口返回的状态码用
HttpStatus.FOUND不符合REST规范,GET查询成功应该返回200 OK,FOUND是302重定向状态码,不建议这么用。
实现方案
第一步:修正AnimalRepository
补全需要的两个查询方法:
@Repository public interface AnimalRepository extends JpaRepository<Animal, Integer> { Optional<Animal> findByNumber(String number); Optional<Animal> findByName(String name); // 按物种查询所有匹配数据 List<Animal> findBySpecies(String species); // 按type字段模糊查询,忽略大小写,匹配任意子串 List<Animal> findByTypeContainingIgnoreCase(String type); }
注意:请确认你的Animal实体类里的物种字段名是species,类型字段名是type,如果字段名不一样,要把方法名里的字段部分改成和实体类字段一致的驼峰写法
第二步:实现第三个按物种查询接口
@GetMapping("/animals/species/{species}") public ResponseEntity<List<Animal>> getSpecies(@PathVariable String species) { List<Animal> animalList = repository.findBySpecies(species); if (animalList.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(animalList, HttpStatus.OK); }
第三步:实现第四个按类型模糊查询接口
@GetMapping("/animals/type/{type}") public ResponseEntity<List<Animal>> getType(@PathVariable String type) { List<Animal> animalList = repository.findByTypeContainingIgnoreCase(type); if (animalList.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(animalList, HttpStatus.OK); }
小优化:可以用@GetMapping注解替代@RequestMapping(method=RequestMethod.GET),代码更简洁
内容的提问来源于stack exchange,提问作者Lenyoung
相关产品推荐
相关产品推荐

