2010-11-17 48 views
2

我有以下表格:休眠地圖<鍵,設置<value>>

@Entity 
@Table(name = "events")  
Event 
    --id 
    --name 

@Entity 
@Table(name = "state")  
State 
    --id 
    --name 

@Entity 
@Table(name = "action")  
Action 
    --id 
    --name 
@Entity 
@Table(name = "state_event_action") 
    StateEventAction 
--id 
--state_id 
--event_id 
--action_id 

我想在state類來獲得的Map<Event, set<StateEventAction>>

我怎麼能做到這一點在Hibernate中map<key, set<value>>

回答

2

如果您想要接收集合的Map,這意味着每個(state_id,event_id)操作都有多個操作。所以你有錯誤的實體映射。它應該是

@Entity 
@Table(name = "state_event_action") 
StateEventAction 
--id 
--state_id 
--event_id 
--Set<action> actions 

在這種情況下,你可以這樣寫:

@Entity @Table(name = "state")  
State 
    --id 
    --name 
Map<Event,StateEventAction> eventActions; 
1

您可能需要首先查詢狀態的所有StateEventAction對象,然後編寫自己的代碼以首先爲事件創建一個集合(如果尚未創建),然後將StateEventAction對象添加到集合中。

State state = // < the state object; 
Query q = Session.createQuery("from StateEventAction sea inner join fetch sea.event where sea.state = :state"); 
q.setEntity("state", state); 

Map<Event, Set<StateEventAction>> map = new HashMap<Event, Set<StateEventAction>>(); 

for(Iterator itr = q.list().iterator(); itr.hasNext();) { 
    StateEventAction sea = itr.next(); 
    Event event = sea.getEvent(); 
    Set<StateEventAction> theSet = map.get(event); 
    if(theSet == null) { 
     theSet = new HashSet<StateEventAction>(); 
     map.put(event, theSet); 
    } 
    theSet.add(sea); 
} 
6

我想在狀態類來獲得Map<Event, Set<StateEventAction>>

Hibernate不支持集合的集合map<key, Set<value>>如列表清單,集合地圖等等。但是你可以實現你自己的UserCollectionType來增加對這種數據結構的支持。這blog post顯示瞭如何使用Apache公用程序的MultiMap實現。

我的建議是使用類似的方法,但也許更喜歡來自Google Guava的基因芯片Multimap

相關問題