2017-02-17 93 views
0
class Category{ 

    @Id 
    @Column(name="ID") 
    private Integer id; 
    private String name; 

    @OneToMany 
    @JoinColumn(name="CATEGORY_ID",referencedColumnName="ID") 
    private Set<Item> items; 

} 

class Item{ 

    private Integer id; 

    @Column(name="CATEGORY_ID") 
    private Integer categoryId; 

    private String name; 

    private String color; 
} 

這裏我有兩個實體(類別爲& Item),它具有一對多的關係。如何在休眠狀態下對兩個加入的實體應用限制

我試圖讓那些在類別ID = 5,項目的color = red項目。 我想結果是這樣的

{ID:5,名稱: '水果' 項目:[{ID:3,名稱: 「番茄」,顏色:紅},{ID:55 ,名稱: 「蘋果」, 顏色: 「紅色」}]}

Criteria c=session.createCriteria("Category.class","cat"); 
c.createAlias("cat.items","it"); 
c.add(Restrictions.eq("cat.id,5)); 
c.add(Restrictions.eq("it.color","red")); 

List<Category> cateList=c.list(); 

但是我得到的類ID = 5的所有項目; 浪費了很多time.Need Help.Thanks

Category    
ID NAME   
1 Flower  
5 Fruit  


Item    
ID CATEGORY_ID NAME COLOR 
3 5   tomato red 
55 5   apple red 
4 5   banana yellow 
6 5   orange orange 
7 5   grape green 
1 1   rose red 
2 1   rose yellow 
+0

請分享表格中的最新數據 – Akshay

回答

1

我將在休眠@Filter@FilterDef註釋看看。

什麼你基本上想要做的就是定義時,他們獲取的,這樣只有那些適用的是集合中適用的顏色謂詞集合中的條目的過濾器。

@Entity 
public class Category { 
    @OneToMany 
    @Filter(name = "itemsByColor") 
    private Set<Item> items; 
} 

@Entity 
@FilterDef(name = "itemsByColor", 
    defaultCondition = "color = :color", 
    parameters = { @ParamDef(name = "color", type = String.class) }) 
public class Item { 
    private String color; 
} 

你需要做的是執行查詢前啓用過濾器:

session.enableFilter("itemsByColor") 
     .setParameter("color", "red"); 

現在執行查詢:返回現在應該只包含Item小號

Criteria c=session.createCriteria("Category.class","cat"); 
c.createAlias("cat.items","it"); 
c.add(Restrictions.eq("cat.id,5)); 
c.add(Restrictions.eq("it.color","red")); 
List<Category> cateList=c.list(); 

Category實例其顏色爲red

注意,當啓用過濾器,它仍然在爲會議期間的作用。

對於這樣的一個查詢啓用過濾器有時會很有用,並且在檢索結果後立即將其禁用,以避免Category對其他查詢的錯誤結果。

相關問題