我试图用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;
}
@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;
}
我用以下代码持久化对象:
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'
从日志来看,它似乎试图先持久化子项,但在这个TestFKChild表中,我在TestFKParent父项上有一个外键。
在JPA/Hibernate中,描述这种关系的正确方法是什么?