首页 > 解决方案 > Spring Boot 中的标准 API

问题描述

我有以下(简化的)实体结构:

public class Animal {
  private long id;
  private int regionId;
  private int categoryId;
  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "animal")
  private List<Attributes> attributes;
}

public class Attributes {
  private long id;
  @ManyToOne(fetch = FetchType.LAZY)
  private Animal animal;
  private String name;
  private String value;
  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  private Detail detail;
}

public class Detail {
  private long id;
  private String size;
  private String type;
}

这是 Spring Boot 应用程序的一部分。

我想要实现的是通过Animal自己的属性和Details中的属性来查询。

我的查询需要如下所示:

GET: /animal/{regionId}/{categoryId}?size=medium,large&type=carnivorous,herbivore

这意味着我需要请求所有具有特定 regionId 和 categoryId 并且在提供的值列表中具有大小和类型的详细信息的动物。另外 - 我认为这是棘手的部分 -大小类型参数是可选的,因此查询需要考虑到这一点。

目前我有一个扩展 CrudRepository 并为Plan实体提供基本查询方法的 PlanRepository。

我试图围绕 Criteria API 寻找一种方法来使用它来实现这一目标,但我不明白如何将所有这些都放在我的存储库中。有任何想法吗?

标签: javaspringspring-bootjpaspring-data-jpa

解决方案


你应该看看 Spring Data JPA Specifications:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications

您必须从 JpaSpecificationExecutor 扩展您的存储库

public interface CustomerRepository 
       extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
 …
}

然后是一个采用 Specification 参数的 findAll 方法:

List<T> findAll(Specification<T> spec);

然后,您可以根据 URL 中传递的参数创建规范:

public static Specification<Animal> bySizeAndType(String size, String type) {

    return new Specification<Animal>() {

      public Predicate toPredicate(Root<Animal> root, CriteriaQuery<?> query,
            CriteriaBuilder builder) {

         // JOIN Attributes
         // JOIN Detail

         if (size != null) {
           // add condition
         }
         if (type != null) {
           // add condition
         }

         return builder.where(...);
      }
    };
  }

我希望这有帮助。


推荐阅读