1
我想用JPA創建兩個類之間的一對一關聯,一個是父級,另一個是子級,帶有發電機,以確保它們具有相同的主鍵:與共享主鍵的雙向一對一關係的外鍵約束違規
@Entity
public class TestFKParent {
@Column(name="code", nullable=false)
@Id
private String code;
@OneToOne(mappedBy="parent", targetEntity=TestFKChild.class, optional=false)
@org.hibernate.annotations.Cascade({CascadeType.ALL})
@PrimaryKeyJoinColumn
private TestFKChild child;
// getters and setters
}
和
@Entity
public class TestFKChild {
@Column(name="id", nullable=false)
@Id
@GeneratedValue(generator="MyGen")
@org.hibernate.annotations.GenericGenerator(name="MyGen",
strategy="foreign",parameters = @Parameter(name = "property", value = "parent"))
private String ID;
@OneToOne(targetEntity=TestFKParent.class, optional=false)
@org.hibernate.annotations.Cascade({})
@PrimaryKeyJoinColumn
private TestFKParent parent;
// getters and setters
}
我堅持的對象與此代碼:
public void testMerge() throws Exception
{
TestFKParent parent = new TestFKParent();
parent.setCode("foo");
TestFKChild child = new TestFKChild();
parent.setChild(child);
child.setParent(parent);
em.merge(parent);
}
但不幸的是我得到一個外鍵衝突:
com.sybase.jdbc3.jdbc.SybSQLException: Foreign key constraint violation occurred, dbname = 'MYDB', table name = 'TestFKChild', constraint name = 'FKE39B2A659CF5145B'
望着日誌,現在看來,這首先嚐試堅持的孩子,但這是我對TestFKParent父一個外鍵此TestFKChild表。
在JPA/Hibernate中描述這種關係的正確方法是什麼?