【问题标题】:hibernate map<key, set<value>>休眠地图<键,设置<值>>
【发布时间】:2010-11-17 08:44:22
【问题描述】:

我有以下表格:

@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&lt;key, set&lt;value&gt;&gt; 的Map&lt;Event, set&lt;StateEventAction&gt;&gt;

如何在 Hibernate 中做到这一点?

【问题讨论】:

    标签: java hibernate hibernate-mapping


    【解决方案1】:

    我想在状态类中获得map&lt;key, Set&lt;value&gt;&gt; of Map&lt;Event, Set&lt;StateEventAction&gt;&gt;

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

    我的建议是使用类似的方法,但可能更喜欢 Google Guava 的通用 Multimap。

    【讨论】:

      【解决方案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;
      

      【讨论】:

        【解决方案3】:

        您可能需要首先查询所有 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);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-06-15
          • 1970-01-01
          • 1970-01-01
          • 2012-02-05
          • 2013-02-09
          • 1970-01-01
          • 2013-03-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多