Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top