繁体   English   中英

Spring Boot中的Criteria API

[英]Criteria API in Spring Boot

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

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中的属性来查询Animal

我的查询需要看起来像这样:

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

这意味着我需要请求所有具有特定regionId和categoryId以及在提供的值列表中具有大小和类型的Details的动物。 而且-我认为这是最棘手的部分-的大小类型参数是可选的,所以查询需要考虑到这一点。

当前,我有一个PlanReposiory,它扩展了CrudRepository并提供了Plan实体的基本查询方法。

我试图围绕Criteria API寻求解决方案,以找到一种使用它来实现此目标的方法,但是我不知道如何将所有这些都放入存储库中。 有任何想法吗?

您应该看看Spring Data JPA规范:

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(...);
      }
    };
  }

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM