首页 > 解决方案 > 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

标签: springspring-data-jpa

解决方案


您可以使用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);
    }
}

推荐阅读