外键约束违反与共享主键的双向一对一关系

时间:2010-11-26 16:34:45

标签: java hibernate jpa sybase

我正在尝试使用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'

查看日志,似乎它首先尝试保留子节点,但是在TestFKChild表中,我在TestFKParent父节点上有一个外键。

在JPA / Hibernate中描述这种关系的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您已经提到过您正在尝试在父母和孩子之间建立一对一的关系。

我想知道 why are you keeping Parent class as a memeber variable in Child class?