我在 Customer
之间建立了一对一的关系。和 ShippingAddress
.我想确保如果 Customer
被删除,ShippingAddress
也被删除,因此我想存储 customer
的 key 在 shipping_address
table 。我只需要从客户导航到地址,即关系不需要是双向的。
根据this JPA guide ,关系应该像这样映射:
@Entity
public class Customer{
@OneToOne
private ShippingAddress shippingAddress;
}
但是,这会导致
shipping_address
的 key 存储在 customer
.我对此的反对意见是它允许某人在 shipping_address
中插入一行。不将其与 customer
关联.同样,它允许某人删除 customer
中的一行。而不删除关联的地址。是否可以创建一个单向的一对一映射,其中
最佳答案
尝试这个:
@Entity
public class Customer {
@Id
private long id;
@OneToOne(mappedBy="customer")
private ShippingAddress shippingAddress;
//...
}
@Entity
public class ShippingAddress {
@Id
private long id;
@OneToOne
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;
//...
}
关于java - 指定单向 @OneToOne JPA 映射的所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59033580/