I have the following entities... Customer
, Card
and Address
Customer:
{
private String cust_id; // Primary key
.....
@OneToOne
Address address; // I want to load address of the customer.
// Can change the association to @OneToMany, if needed
}
Card:
{
private String card_id; // Primary Key
private String cust_id; // Foreign Key to Customer.cust_id
....
}
Address:
{
private String card_id; // Foreign key to card.card_id
private String address1;
.....
}
When I load customers I want to load Addresses with association table Card
. But the tricky part is Address
does not have a primary key. It only has a Foreign key.
You could use the annotation @JoinTable after the @OneToOne to point the card's table, so you won't need an entity for card, but if the card's table isn't just a relational table, you could map card in User as @OneToOne and have a @Transient 'getAddress()' method that returns 'this.card.getAddress()', but on card's entity you must map the relation between Address and Card(@OneToOne(mappedBy='card_id')), and in Address you could map card_id as @Id.
First Alternative
Customer:
@OneToOne
@JoinTable(name="card", joinColumns = @JoinColumn(name="cust_id"),
inverseJoinColumns = @JoinColumn(name="card_id"))
private Address address;
Second alternative
Customer:
@OneToOne(mappedBy="cust_id")
private Card card;
...
@Transient
public Address getAddress(){
return this.card == null ? null : this.card.getAddress();
}
Card:
@OneToOne(mappedBy="card_id")
private Address address;
Address:
@Id
private String card_id;
In the Second case Card has a Embedded pk which is formed by two fks(Customer and Address)
Card:
@EmbeddedId
private CustomerAddressPK id;
CustomerAddressPK
@Embeddable
public class CustomerAddressPK(){
private String cust_id;
private String card_id;
}
The mapping between Customer
and Address
can be made by using the concept of Dependent objects.
Look at the documentation, you will find similar example where there is a mapping between Person
entity with dependent object called Name
.