我有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&amp;由于它的id已经设置,因此抛出异常:
org.hibernate.PersistentObjectException: detached entity passed to persist
您是否可以告诉我如何在不必再次坚持B的情况下坚持这种情况下的关联?
答案 0 :(得分:0)
为什么不尝试设置a而不是b?
你也可以在一个空格中清空它,所以它不会试图坚持它。
编辑:正如评论中所述,它没有预期的效果。您应该使用saveOrUpdate()
中建议的persist()
代替 obj = { getAcceptedIssuers : function() { return null; }, checkClientTrusted: function() { return; }, checkServerTrusted: function() { return; } };
var o = new JavaAdapter(javax.net.ssl.X509TrustManager, obj);
var oo = new Array();
oo.push(o);