您如何定义以下实体之间的双向映射:
@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,
)
答案 0 :(得分: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;
}