spring - Spring Boot - 从存储库 jpa 获取共同的属性
问题描述
我开始使用 spring boot 的 rest API 并最终在返回最后两个主题时遇到了一些具体问题
1- GET animals/number/{number} 您应该列出带有数字/代码 {number} 的动物
2- GET animals/name/{name} 您应该列出名称为 {name} 的动物
3- 获取动物/物种/{species} 您应该列出物种 {species} 的动物。请注意,每个物种可以归还不止一只动物。
4- 获取动物 /type/{type} 您应该列出 {type} 类型的动物。请注意,每种类型可以返回不止一种动物。由于该字段的性质,您应该执行子字符串搜索。例如,{type} 的值“poison”应该返回类型为“reptile/Poison”的动物。
我得到了什么
@RequestMapping(value="/animals/number/{number}", method=RequestMethod.GET)
public ResponseEntity<?> getNumber(@PathVariable(name = "number") String number) {
Optional<Animal> o = repository.findByNumber(number);
if (!o.isPresent())
return new ResponseEntity<>(o, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(o, HttpStatus.FOUND);
}
@RequestMapping(value="/animals/name/{name}", method=RequestMethod.GET)
public ResponseEntity<?> getName(@PathVariable(name = "name") String name) {
Optional<Animal> o = repository.findByName(name);
if (!o.isPresent())
return new ResponseEntity<>(o, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(o, HttpStatus.FOUND);
}
我尝试做主题 3,但我无法:
@RequestMapping(value="/animals/species/{species}", method=RequestMethod.GET)
public ResponseEntity<?> getSpecies(@PathVariable(name = "species") String species) {
List<Animal> p = repository.findAll();
if (species == null)
repository.findAll().forEach(p::contains);
else
repository.findByTitleContaining(species).forEach(p::contains);
if (p.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(p, HttpStatus.OK);
}
@Repository
public interface AnimalRepository extends JpaRepository<Animal, Integer> {
Optional<Animal> findByNumber(String number);
Optional<Animal> findByName(String name);
Optional<Animal> findByspecie(String species);
}
我进行测试 //localhost:8081/animals/name/Animalname
解决方案
您可以使用Spring Data生成的查询(正如您似乎已经定义的那样)查询与搜索物种匹配的所有动物:
List<Animal> findByTitleContaining(String specie);
java.util.stream.Collectors#groupingBy
然后您可以使用以下类型对返回的元素进行分组Animal
:
@RequestMapping(value="/animals/species/{species}", method=RequestMethod.GET)
public ResponseEntity<?> getSpecies(@PathVariable(name = "species") String species) {
List<Animal> matchingAnimals = repository.findByTitleContaining(species);
if (!matchingAnimals.isEmpty()) {
final Map<String, List<Animal>> groupedAnimals = matchingAnimals.stream()
.collect(Collectors.groupingBy(Animal::getType));
return new ResponseEntity<>(groupedAnimals, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
推荐阅读
- python - 遍历 google sheet/excel 列字母
- html - 如何在 FireFox 浏览器中隐藏滚动条(同时能够滚动)?
- reactjs - 如何将返回类型字符串转换为十进制数?
- angular-cdk - cdk-virtual-scroll-viewport 用于水平和垂直滚动
- swift - Swift 类的闭包中的数据如何流动
- javascript - 反应导航栏链接没有响应
- autodesk-forge - 如果模型部分加载,为什么查看器会显示损坏的几何图形?
- azure - 如何使用没有 mail.send 权限的 MS Graph 设置 FROM(代表)邮件
- java - 如何更改 Visual Studio 代码 python 位置
- flutter - Flutter 将 3 个不同的计数器类都放在 1 个计数器中