代码之家  ›  专栏  ›  技术社区  ›  Cyrille Ka

具有共享主键的双向一对一关系的外键约束冲突

  •  1
  • Cyrille Ka  · 技术社区  · 14 年前

    我试图用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 回复  |  直到 14 年前
        1
  •  0
  •   Dinesh    14 年前

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

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