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中描述这种关系的正确方法是什么?