我有一个模型:
@Entity
class A {
@ManyToOne
B b;
int i;
}
@Entity
class B {
@OneToMany(mappedBy="b")
List< A > list = new ArrayList< A >();
}
现在在我的 EJB 服务中,我这样做:
void f(Aid,Bid){
A a = em.find(A.class, Aid);
B b = em.find(B.class, Bid);
a.setB(b);
}
这会引发 db 约束异常(INSERT INTO B VALUES... WITH SAME VALUES THAT ALREADY EXIST IN CURRENT B)。
- 为什么在 B 表中已经存在且关系不是 PERSIST 的情况下尝试向 B 插入新记录?
笔记:
1 当我在最后一行之后做:
em.merge(a);
它也工作......???
2 当我这样做时a.setI(1)
;没有合并 - 它在 DB 中发生了变化(就像我想的那样)
谢谢!!!