开发者

Foreign Key constraint violation with bidirectional one-to-one relationship with shared primary key

开发者 https://www.devze.com 2023-01-26 21:56 出处:网络
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:

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号