[英]Mapping a OneToMany unidirectional relationship
Considering these tables as example, where each person
can have multiple address
es. 以这些表为例,每个
person
可以有多个address
。
CREATE TABLE person (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE address (
id INTEGER NOT NULL PRIMARY KEY,
address VARCHAR(100) NOT NULL,
city VARCHAR(100) NOT NULL,
person_id INTEGER NOT NULL
);
I would like to map these tables to JPA entities, but I wouldn't like to map a bidirectional relationship between them using mappedBy
. 我想将这些表映射到JPA实体,但是我不想使用
mappedBy
映射它们之间的双向关系。
What's the proper way to map a OneToMany
unidirectional relationship between Person
and Address
? 在
Person
和Address
之间映射OneToMany
单向关系的正确方法是什么? Considering that the Person
must know their Address
es, but the Address
must not know the Person
it belongs to. 考虑
Person
必须知道其Address
es,但该Address
必须不知道其所属的Person
。
You can do it using annotations JoinColumn and ManyToOne in Person Entity. 您可以使用“个人实体”中的注释JoinColumn和ManyToOne进行注释。
@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)
@JoinColumn(name = "person_pkey")
public List<Address> getAddresses() {
return addresses;
}
You don't need to make it bidirectional. 您无需使其双向。 You can simply place the
@OneToMany
annotation on you collection-typed field in Person
and specify the JoinColumn
of the address
table. 您只需将
@OneToMany
批注放置在Person
集合类型的字段上,然后指定address
表的JoinColumn
。
See here , Example 3. I think that's what you're looking for. 请参见此处的示例3。我认为这就是您想要的。
So you will have something like: 因此,您将获得类似以下内容的信息:
// In Person class:
@OneToMany
@JoinColumn(name="person_id")
public Set<Address> getAddresses() {return addresses;}
No mappedBy
attribute, no bidirectional mapping. 没有
mappedBy
属性,没有双向映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.