- Foreign key relationship. Customer has a foreign key to UserProfile.
- Shared primary key. The MarketingPreferences entity is set to use the same primary key as the customer, so its primary key is also a foreign key to the customer.
- Join table. Customer and wishlist are linked by a join table, appropriate if the association is optional.
mvn test
I’ll quickly explain how each type of association is mapped.
The relationship between Customer and UserProfile is a foreign key, which is the default for a one to one association, so you simply need the @OneToOne annotation in the Customer class:
private UserProfile userProfile;
@OneToOne(cascade = CascadeType.ALL)
public UserProfile getUserProfile() {
return userProfile;
}
Then, if you want to make the association bidirectional, in the UserProfile class, add a Customer instance variable, but specify that the association is mapped and controlled by the userProfile instance variable in the Customer class. This is the standard set up for bi-directional associations – you must not define the association on both sides, as this would actually create two associations. The code in UserProfile is:
@OneToOne(mappedBy = "userProfile")
public Customer getCustomer() {
return customer;
}
private Long id;
private Customer customer;
@Id
public Long getId() {
return id;
}
@MapsId
@OneToOne
public Customer getCustomer() {
return customer;
}
To make this bidirectional, on the Customer side, you must tell Hibernate to use the primary key of MarketingPreferences when it joins the database tables:
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
public MarketingPreferences getMarketingPreferences() {
return marketingPreferences;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinTable( name = "CUSTOMER_WISHLIST",
joinColumns = @JoinColumn( name = "CUSTOMER_ID"),
inverseJoinColumns = @JoinColumn( name = "WISHLIST_ID"))
public Wishlist getWishlist() {
return wishlist;
}
@OneToOne(mappedBy = "wishlist")
public Customer getCustomer() {
return customer;
}