Object-oriented languages represent associations using object references; but inthe relational world, an association is represented as a foreign key column, withcopies of key values (and a constraint to guarantee integrity). There are substan-tial differences between the two representations.

Object-oriented languages represent associations using object references; but in the relational world, an association is represented as a foreign key column, with copies of key values (and a constraint to guarantee integrity). There are substantial differences between the two representations.

Object references are inherently directional; the association is from one object to the other. They’re pointers. If an association between objects should be navigable in both directions, you must define the association twice, once in each of the associated classes.

public class User {
  private Set billingDetails;
  ...
}
public class BillingDetails {
  private User user;
  ...
}

On the other hand, foreign key associations aren’t by nature directional. Navigation has no meaning for a relational data model because you can create arbitrary data associations with table joins and projection. The challenge is to bridge a completely open data model, which is independent of the application that works with the data, to an application-dependent navigational model, a constrained view of the associations needed by this particular application.

It isn’t possible to determine the multiplicity of a unidirectional association by looking only at the Java classes. Java associations can have many-to-many multiplicity.

public class User {
  private Set billingDetails;
  ...
}
public class BillingDetails {
  private Set users;
  ...
}

Table associations, on the other hand, are always one-to-many or one-to-one. You can see the multiplicity immediately by looking at the foreign key definition. The following is a foreign key declaration on the BILLING_DETAILS table for a one-to-many association (or, if read in the other direction, a many-to-one association):

USER_ID bigint foreign key references USERS

These are one-to-one associations:

USER_ID bigint unique foreign key references USERS
BILLING_DETAILS_ID bigint primary key foreign key references USERS

If you wish to represent a many-to-many association in a relational database, you must introduce a new table, called a link table. This table doesn’t appear anywhere in the domain model. For our example, if we consider the relationship between the user and the billing information to be many-to-many, the link table is defined as follows:

create table USER_BILLING_DETAILS (
USER_ID bigint foreign key references USERS,
BILLING_DETAILS_ID bigint foreign key references BILLING_DETAILS,
PRIMARY KEY (USER_ID, BILLING_DETAILS_ID)
)

Source: Manning - Java Persistence With Hibernate, page 16-17