2010-07-10 60 views
4

我有一個叫做Event的Hibernate實體,它有一個一對多的元數據實體EventData。使用Criteria休眠一對多搜索

鑑於以下事件:

事件ID:1
EventHash:西蘭花

用下面EventDatas:

EventDataId:1
事件ID:1
場:標籤
內容:tagme

EventD ataId:2個
事件ID:1
場:標籤
內容:anotherTag

如何創建一個標準的查詢檢索其中有兩個標籤「anotherTag」和「塔格梅」事件?在SQL中,我加入了EVENT_DATA表一次,所搜索的每一個標籤,但我只能似乎創造一個別名Event.EventData關係,即

int inc = 0; 

Conjunction junc = Restrictions.conjunction(); 

for (String tag : tags) { 
    crit.createAlias("e.EventData", "ed"+inc); 
    junc.add(
     Restrictions.and(
      Restrictions.eq("ed"+inc+".field", "tag"), 
      Restrictions.eq("ed"+inc+".content", tag) 
     ) 
    ); 
    inc++; 
} 

不工作; duplicate association path: Event.EventData

同樣,一個正常的連詞是不行的,因爲該條款最終成爲:

((ed3_.field='tag' and ed3_.content='anotherTag') and (ed3_.field='tag' and ed3_.content='tagme')) 

和,可悲的是,數據庫中的字段不能在同一時間有兩個不同的值。

任何想法,我可以如何清理這個,或者是唯一的選擇恢復到HQL?

回答

4
List fields = new ArrayList(1); 
fields.add("tag") 

List contents = new ArrayList(tags.size()); 
for (String tag : tags) { 
    contents.add(tag); 
} 

session.createCriteria(Event.class); 
criteria.createCriteria("eventDatas").add(Restrictions.and(Restrictions.in("field", fields), Restrictions.in("content", contents))); 

/*如果字段的大小始終是一個,你可以使用Restrictions.eq( 「域」, 「標籤」)也*/

+0

精湛,謝謝! – Martin 2010-08-27 09:37:48