2

我有以下表格:

@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<key, set<value>>Map<Event, set<StateEventAction>>

我怎样才能在休眠中做到这一点?

4

3 回答 3

6

我想在州级map<key, Set<value>>上课Map<Event, Set<StateEventAction>>

Hibernate 不支持开箱即用的集合集合,例如 List of Lists、Map of Sets 等。但是您可以实现自己的UserCollectionType以添加对这种数据结构的支持。这篇博客文章MultiMap展示了如何使用Apache commons的实现来做到这一点。

我的建议是使用类似的方法,但可能更喜欢MultimapGoogle Guava 的泛型。

于 2010-11-17T11:36:21.323 回答
2

如果你想收到集合的地图,这意味着每个(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;
于 2010-11-17T11:03:49.800 回答
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);
}
于 2010-11-17T09:00:26.797 回答