【问题标题】:Map problem with JPA / Hibernate / PGJPA / Hibernate / PG的映射问题
【发布时间】:2009-01-19 15:48:46
【问题描述】:

我有两个实体,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。

【问题讨论】:

  • 第 3 行有错字吗?实体不应该是 e1 吗?
  • 另外,回答这个问题需要查看持久实体的注释方式。
  • 修复了错误,并添加了持久化实体类代码。

标签: java hibernate exception jpa


【解决方案1】:

您的代码中有一些奇怪之处...但您似乎应该在 Entity1 中添加 @MapKey 注释:

(snippet)
@OneToMany(mappedBy = "e1", fetch = FetchType.EAGER)
@MapKey(name="iCantFigureTheRightPropertyName")
public Map<String, Entity2> getE2s() {  
    return e2s;  
}  

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多