休眠映射<键,设置<值>>
-
25-09-2019 - |
题
我有以下表格:
@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;
其他提示
您可能需要先查询所有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);
}
不隶属于 StackOverflow