2017-03-17 32 views
0

我正在面臨一個問題,通過來自列表中的子項的值來過濾實體。 例如:帶規範的JPA - 如何通過子集合內容過濾實體?

public class Father(){ 
    private String name; 
    private Set<Child> childs; 
} 
public class Child(){ 
    private String name; 
    private Integer age; 
    private School school; 
} 
public class School(){ 
    private String name; 
} 

我想過濾所有的父親已經在學校十一個孩子

這是我做的,但不能正常工作:

Specification specs = new Specificatrion(){ 
     @Override 
     public Predicate toPredicate(Root<Father> root, CriteriaQuery<?> query, final CriteriaBuilder cb){ 
      Root<Child> childRoot = query.from(Child.class); 
      Path<?> path = childRoot.get(Child_.school.name); 
      Predicate pred = exp.in("School Name"); 
      return cb.and(pred); 
     } 
} 

能有人幫我解決這個問題嗎? 謝謝!

回答

0

你必須在你的孩子身上有一個反向關係,回到父親那裏,這樣孩子才能在學校和父親之間架起橋樑。

像這樣將工作:

@Entity 
public class Father { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    private String name; 

    @OneToMany(mappedBy = "father", cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
    private Set<Child> childs = new HashSet<>(); 


@Entity 
public class Child { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    private String name; 
    private Integer age; 

    @ManyToOne(cascade=CascadeType.ALL) 
    private Father father; 

    @OneToOne(cascade = CascadeType.PERSIST) 
    private School school; 

然後在您的FatherRepository:

@Query("select father from Child child join child.father father join child.school school where school.name=:school") 
List<Father> findBySchool(@Param("school") String school); 
+0

嗨埃塞克斯, 我想使用規範。 將嘗試改變,看看會發生什麼, 謝謝! –

+0

您可以使用規格,但我不認爲您可以像您在問題中設定的一樣。很高興被證明是錯誤的。 –