我有以下表格:

@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>>

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

有帮助吗?

解决方案

如果你想收到的套地图,就意味着有每个(STATE_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;

其他提示

我想在国家级获得 map<key, Set<value>>Map<Event, Set<StateEventAction>>

Hibernate 不支持开箱即用的集合集合,例如列表列表、集合映射等。但你可以实现你自己的 UserCollectionType 添加对这种数据结构的支持。这 博客文章 展示了如何使用 MultiMap 来自 Apache commons 的实现。

我的建议是使用类似的方法,但也许更喜欢通用的方法 Multimap 来自谷歌番石榴。

您可能需要先查询所有StateEventAction对象的状态,那么编写自己的代码首先创建了一套如果尚未创建,则StateEventAction obejct添加到该集合的事件。

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top