0

您将如何定义以下实体之间的双向映射:

@Entity
class Host {
    @Id 
    String id;

    HaGroup haGroup;  // needs mapping
}

@Entity
class HaGroup {
    @Id 
    String id;

    @OneToOne(optional = false)
    @JoinColumn(name = "primary_host_id")    
    Host primary;

    @OneToOne(optional = false)
    @JoinColumn(name = "secondary_host_id")
    Host secondary;
}

我想 HaGroup 应该是协会的所有者,所以 @JoinColumn 在这里工作得很好,但我坚持相反的方向。我希望在 Host 对象中拥有对主机所属的 HaGroup(作为主要主机或辅助主机)的引用,或者如果它不是任何 HaGroup 的成员,则为 null。

有什么想法可以优雅地完成吗?

Host 和 HaGroup DB 表定义如下:

CREATE TABLE host
(
  id character(32) NOT NULL,
  CONSTRAINT host_pkey PRIMARY KEY (id ),
)

CREATE TABLE ha_group
(
  id character(32) NOT NULL,
  primary_host_id character(32) NOT NULL,
  secondary_host_id character(32) NOT NULL
  CONSTRAINT ha_group_pkey PRIMARY KEY (id ),
  CONSTRAINT fk_ha_group_p_host_dc FOREIGN KEY (primary_host_id)
      REFERENCES host (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
  CONSTRAINT fk_ha_group_s_host_dc FOREIGN KEY (secondary_host_id)
      REFERENCES host (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
)
4

1 回答 1

0

这取决于您希望从主机端获得什么关系。我建议你像下面这样的设计

@Entity
class Host {
    @Id 
    String id;

    HostType type;// this is a enum with values(PRIMARY,SECONDARY)
    @ManyToOne
    HaGroup haGroup;  // needs mapping
}

@Entity
class HaGroup {
    @Id 
    String id;

    @OneToMany(mappedBy="haGroup")
    @JoinColumn(name = "primary_host_id")    
    List<Host> hostList;

}
于 2013-06-07T10:11:19.127 回答