0

我有一个现有的具有属性的子实体。现在,我想为父实体中子实体的两个属性添加外键约束。以下是SQL

CREATE TABLE parent( 
   parent_id1 int
   parent_id2 int
   CONSTRAINT parent_pk PRIMARY KEY (parent_id_1,parent_id_2);
);

CREATE TABLE child(

   c_id INT PRIMARY KEY,

   parent_id_1 int,
   parent_id_2 int,
   constraint fk foreign key(parent_id_1,parent_id_2) references parent(parent_id_1,parent_id_2)
);

我有Child实体

@Entity
class Child implements Serializable {
    @Id
    Integer cId;
    Integer parentId1;
    Integer parentId2;
// Getters and Setters
}
// Parent Key
@Embeddable
class ParentPk {
    Integer parentId1;
    Integer parentId2;

    // Getters, Setters, Equals and Haschode
}


// Parent Entity
@Entity
class Parent{

   @EmbeddedId
   ParentPk pKey;

   // Getters and Setters
}

我正在寻找的是,添加从 Parent 到 Child 的单向关系作为propertyin Parent

4

1 回答 1

0

我使用以下解决方案解决了它:


// Parent Entity
@Entity
class Parent{

   @EmbeddedId
   ParentPk pKey;


   @OneToMany
   @JoinColumns({@JoinColumn(name = "parent_id1",
                    referencedColumnName = "parent_id1"),
            @JoinColumn(name = "parent_id2", referencedColumnName = "parent_id2")
    }
    )
    private List<Child> Child;

   // Getters and Setters
}

于 2019-12-27T17:23:46.327 回答