4

我有两个实体,Entity1 和 Entity2,是一对多的关系。在 Entity1 上,我有一个包含条目的地图。

我用来在地图上保留一个带有一些 Entity2 的新 Entity1 的代码是这样的:

   Entity1 e1 = new Entity1();  
   Entity2 e2 = null;  
   e1.setE2s(new HashMap<String, Entity2>());
   for (String key : someKeySet()){
      e2 = new Entity2();
      e2.setCode(key);                      
      e2.setSwhon(true);        
      e2.setE1(e1);
      e1.getE2s(key, e2);       
      em.persist(e1.getE2s().get(key));         

    }       
    em.persist(e1);
    em.flush();

这是实体的摘录:

@Entity
@Table(name = "wm_Entities1")  
public class Entity1 implements Serializable {  
   private static final long serialVersionUID = 6592708276573465599L;  
   private Map<String, Entity2> e2s;
   private Long id;  
   @Id  
   @GeneratedValue(strategy=GenerationType.TABLE)  
   public long getId() {  
    return id;  
   }  
   public void setId(long id) {  
    this.id = id;  
   }  
   public void setE2s(Map<String, Entity2> e2s){    
    this.e2s = e2s;
   }       
   @OneToMany(mappedBy = "e1", fetch = FetchType.EAGER)  
   public Map<String, Entity2> getE2s() {  
    return e2s;  
   }  
}

@Entity
@Table(name = "wm_Entities2")
public class Entity2 implements Serializable {  
    private static final long serialVersionUID = -6131765066573346790L; 
    private long id;
    private Entity1 e1;
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
    @ManyToOne()
    @JoinColumn(name="e1_id")
    public Entity1 getE1() {
        return this.e1;
    }
    public void setE1(Entity1 e1) {
        this.e1 = e1;
    }
}

这似乎工作正常,因为它在 pg 数据库上插入两个实体,但问题是它没有在数据库上创建 - 保存 e2 的 MapKey(理论上 JPA​​ 生成这个密钥),所以当我得到 e1 回来时,我尝试从中获取 e2s 地图,我有一个:

javax.ejb.EJBException:org.hibernate.HibernateException:集合的空索引列:

我怎样才能得到这个 MapKey 保存?

注意:我正在使用带有 JPA/Hibernate 的 JavaEE,在 JBoss 4.2 上运行,带有 PGSQL DB。

4

1 回答 1

2

There are some oddities in your code... But it seems that you should add a @MapKey annotation in Entity1:

(snippet)
@OneToMany(mappedBy = "e1", fetch = FetchType.EAGER)
@MapKey(name="iCantFigureTheRightPropertyName")
public Map<String, Entity2> getE2s() {  
    return e2s;  
}  
于 2009-01-20T11:42:26.317 回答