我有一个Order具有billingAddress和的实体shippingAddress。我也有一个Address实体。我试图使单个地址表同时包含送货地址和帐单地址,因为没有什么区别它们,并且在一个或多个订单中帐单地址和送货地址可以相同。我已经在中使用@ManyToOne了地址字段Order,但是我不确定使这种双向传输正确的方法。
Order
billingAddress
shippingAddress
Address
@ManyToOne
我有两个问题:
码:
@Entity @Table(name = "orders") public class Order { //... private Address shippingAddress; private Address billingAddress; @ManyToOne @JoinColumn(name = "shipping_address_id", referencedColumnName = "address_id", nullable = false) public Address getShippingAddress() { return shippingAddress; } @ManyToOne @JoinColumn(name = "billing_address_id", referencedColumnName = "address_id", nullable = false) public Address getBillingAddress() { return billingAddress; } //... } @Entity @Table(name = "addresses") public class Address { //address1, address2, city, state, etc. //how to link back to Orders? private Set<Order> orders; }
关于您的第一个问题:它是ManyToOne吗?
这取决于。如果多个订单可以具有相同的收货地址,则为ManyToOne。如果只有一个订单可以具有给定的送货地址,则为OneToOne。帐单地址也一样。
我不确定使双向关联是一个好主意。在这种情况下,我可能不会这样做。但是,如果你想让它是双向的,那么你必须让 他们 双向的。您确实在这里有两个不同的关联。因此,映射如下所示:
@OneToMany(mappedBy = "shippingAddress") private Set<Order> shippedOrders; @OneToMany(mappedBy = "billingAddress") private Set<Order> billedOrders;
或者,如果该关联实际上是一个OneToOne(请参阅第一个问题的答案):
@OneToOne(mappedBy = "shippingAddress") private Order shippedOrder; @OneToOne(mappedBy = "billingAddress") private Order billedOrder;