Considering these tables as example, where each person
can have multiple address
es.
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
.
What's the proper way to map a OneToMany
unidirectional relationship between Person
and Address
? Considering that the Person
must know their Address
es, but the Address
must not know the Person
it belongs to.
You can do it using annotations JoinColumn and ManyToOne in Person Entity.
@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.
See here , Example 3. I think that's what you're looking for.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.