I am trying to create with JPA a one-to-one association between two classes, one being the parent, and the other the child, with a generator to make sure they have the same primary key:
@Entity
public class TestFKParent {
@Column(name="code", nullable=false)
@Id
private String cod开发者_StackOverflow中文版e;
@OneToOne(mappedBy="parent", targetEntity=TestFKChild.class, optional=false)
@org.hibernate.annotations.Cascade({CascadeType.ALL})
@PrimaryKeyJoinColumn
private TestFKChild child;
// getters and setters
}
and
@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
}
I persist the objects with this code:
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);
}
But unfortunately I obtain a foreign key violation:
com.sybase.jdbc3.jdbc.SybSQLException: Foreign key constraint violation occurred, dbname = 'MYDB', table name = 'TestFKChild', constraint name = 'FKE39B2A659CF5145B'
Looking at the logs, it seems it tries to persist the child first, but this is in this TestFKChild table that I have a foreign key on the TestFKParent parent.
What is the proper way to describe this kind of relationship in JPA/Hibernate?
You have mentioned that you are trying to create one on one relationship between parent and child.
Here I wanted to know
why are you keeping Parent class as a memeber variable in Child class?
精彩评论