문제

I have the following tables:

@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

I would like in state class to get map<key, set<value>> of Map<Event, set<StateEventAction>>

How can I do it in Hibernate?

도움이 되었습니까?

해결책

If you want to recieve Map of sets, it means that there are several actions for each (state_id, event_id) actions. So you have wrong entity's mappings. It should be

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

In this case you can write :

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

다른 팁

I would like in state class to get map<key, Set<value>> of Map<Event, Set<StateEventAction>>

Hibernate does not support collection of collections such as List of Lists, Map of Sets, etc out of the box. But you could implement your own UserCollectionType to add support for this kind of data structure. This blog post shows how to do so using the MultiMap implementation from Apache commons.

My suggestion would be to use a similar approach, but maybe to prefer the generified Multimap from Google Guava.

You will probably need to first query all the StateEventAction objects for the state then write your own code to first create a set for the event if not already created then add the StateEventAction obejct to the set.

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