簡體   English   中英

具有共享主鍵的雙向一對一關系的外鍵約束違規

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

我試圖用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中描述這種關系的正確方法是什么?

您已經提到您正在嘗試在父母與孩子之間建立一對一的關系。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM