[英]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.