我有两个实体,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: null
index column for collection:
如何保存这个MapKey?
注意:我正在使用带有JPA / Hibernate的JavaEE,使用PGSQL DB运行JBoss 4.2.
最佳答案 您的代码中有一些奇怪的东西……但似乎您应该在Entity1中添加@MapKey批注:
(snippet)
@OneToMany(mappedBy = "e1", fetch = FetchType.EAGER)
@MapKey(name="iCantFigureTheRightPropertyName")
public Map<String, Entity2> getE2s() {
return e2s;
}