java - Specifying the owner of a unidirectional @OneToOne JPA mapping
问题描述
I've a one-to-one relationship between Customer
and ShippingAddress
. I want to ensure that if a Customer
is deleted, the ShippingAddress
is also deleted, and therefore I want to store the key of customer
in the shipping_address
table. I only need to navigate from the customer to the address, i.e. the relationship doesn't need to be bidirectional.
According to this JPA guide, the relationship should be mapped like this:
@Entity
public class Customer{
@OneToOne
private ShippingAddress shippingAddress;
}
However, this will cause the key of shipping_address
to be stored in customer
. My objection to this is that it would allow someone to insert a row into shipping_address
without associating it with a customer
. Similarly, it would allow someone to delate a row in customer
without also deleting the associated address.
Is it possible to create a unidirectional one-to-one mapping wherein
- You can navigate from the parent (customer) to the child (shipping address)
- The key of the parent is stored in the child table
解决方案
尝试这个:
@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;
//...
}
推荐阅读
- asp.net - ASP.NET Core SignalR 是否向后兼容 ASP.NET SignalR
- webstorm - 无法让 WebStorm 识别 gsap/TweenLight 库?
- android - 原因:“E:\Linux Data\Android\Sdk\build-tools\27.0.3\aidl.exe”中缺少aidl
- python - python想根据来自另一个单元格的字符串/文本从Excel单元格中提取文本/字符串
- docker - 将 docker 映像复制到 docker-machine 并使其正常工作
- python - 使用 pandas Dataframe Python 对运行摘要进行分组
- android - 奥利奥信标检测
- perl - 有没有办法在 perl if 语句中使用 <=> 运算符?
- user-interface - 这个互动网站是如何制作的?
- java - Oracle 11g,使用 TLSv1.2 与 Java 存储过程的 HTTPS 连接