I have an Order
entity that has a billingAddress
and a shippingAddress
. I also have an Address
entity. I am trying to make a single address table hold both the shipping and billing addresses, since there is nothing to differentiate them, and the billing and shipping address can be the same in one or multiple orders. I have used @ManyToOne
on the address fields in Order
, but I'm not sure of the proper way to make this bidirectional.
I have two questions:
- Is
@ManyToOne
appropriate for the address fields, since it is really an n:2 relationship that I simply am using two separate fields to represent? If not, what should I do instead? - Assuming 1. is OK, how do I make the mapping bidirectional (What annotation(s) should I use in the
Address
entity?)? Can this be done by listing multiple columns in an annotation inAddress
?
Code:
@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;
}
See Question&Answers more detail:os