【发布时间】:2015-08-11 08:04:01
【问题描述】:
我有 3 个表 A、B 和映射表 A_B,其中包含两者的 ID(A_ID 和 B_ID)。以下是映射这 3 个表的 java 类的样子:
@Entity
@Table(name = "A")
public class A {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_A", referencedColumnName="Id", nullable = false)
private Set<A_B> ab;
//Other attributes, Getters Setters etc.
}
@Entity
@Table(name = "A_B")
public class A_B {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_B", nullable = false)
private B b;
//Other attributes, Getters Setters etc.
}
Entity
@Table(name = "B")
public class B {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
//Other attributes, Getters Setters etc.
}
现在假设我已经持久化了 B (b) 的一个对象。现在我想保留一个 A (a) 的对象以及这两者 (ab) 之间的关联。我有我的代码:
@PersistenceContext(unitName = "demoPU")
private EntityManager em;
B b = em.createNamedQuery(queryName, B); // Getting obj of B
A a = new A();
A_B ab = new A_B();
ab.setB(b); // Setting B in relationship
a.setAb(ab);
em.persist(a);
但是这试图再次保持 b 并且由于它的 id 已经设置,所以它抛出异常:
org.hibernate.PersistentObjectException: detached entity passed to persist
你能告诉我如何在这种情况下保持关联而不必再次保持 B 吗?
【问题讨论】: