[英]How to write a Specification Joining Two Tables with where attributes in different classes
啟動應用程序,並需要一個帶有動態where字段的查詢。 谷歌搜索我發現規范可能是一個答案,但make where子句如何在不同類的屬性中搜索?
這是我的模特
品牌類別
@Entity
public class Brand {
@Id
private Long id;
private String name;
@OneToMany(mappedBy="brand",cascade=CascadeType.ALL)
private Set<Cars> cars;
//Getter's and Setters
}
車類
@Entity
public class Car {
@Id
private Long id;
private String name;
private String carType;
@ManyToOne(cascade=CascadeType.ALL)
private brand brand;
//Getter's and Setters
}
倉庫是海峽之一:
public interface CarRepository extends JpaRepository<Car, Long>, JpaSpecificationExecutor<Car> {
}
如果用戶輸入汽車的名稱和品牌,我需要類似以下的jpql
select c from car c join c.brand br where br.name = :brandName and c.name = :carName
用戶也只能輸入汽車的類型,因此jpql將為:
select c from car c join c.brand br where br.name = :brandName and c.carType = :carType
當您需要構建動態查詢時,通常使用規范。 如果您的用例僅限於這兩個查詢,則我寧願將它們寫為靜態查詢,並使用簡單的if / else來檢查是否提供了名稱或類型。
使用規范並遵循Spring指南時,您應該編寫一個具有各種規范的附加類,例如:
public class CarSpecifications {
public static Specification<Car> withBrandName(final String name) {
return (root, query, cb) -> {
final Path<Brand> brandPath = root.get("brand");
return cb.equal(brandPath.<String>get("name"), name);
};
}
// TODO: withName, withType
}
您必須在此處添加多個方法,以上方法僅適用於您的br.name = :brandName
子句。
現在,要使用該類,您必須編寫如下內容:
public List<Car> findCars(String brandName, String name, String type) {
Specifications<Car> spec = Specifications
.<>where(CarSpecifications.withBrandName(brandName));
if (name != null) {
spec.and(CarSpecifications.withName(name);
}
// TODO: if (type != null) ...
return repository.findAll(spec);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.