我开始使用spring boot的rest API,最终在返回最后两个主题时遇到了一些特定的问题
1- GET animals/number/{number}你应该用数字/代码{number}列出动物
2- GET animals/name/{name}您应该列出名称为{name}的动物
3- GET animals/species/{species}你应该列出物种中的动物。注意,每个物种可以返回多个动物。
4- GET动物/type/{type}您应该列出类型为{type}的动物。注意,每种类型可以返回多个动物。由于该字段的性质,您应该执行子字符串搜索。例如,{type}的值"poison"应该返回类型为"reptile/Poison"的动物。
what I got
@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);
}
i put for test//localhost:8081/animals/name/Animalname
您可以使用Spring Data生成的查询(如您似乎已定义的查询)查询与搜索物种匹配的所有动物:
List<Animal> findByTitleContaining(String specie);
然后您可以使用Animal
类型使用java.util.stream.Collectors#groupingBy
对返回的元素进行分组:
@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);
}
}