Relationship Pair

We can think of @ManyToOne as the "one" side of a @OneToMany/@ManyToOne relationship pair.

As such it is the side that maps to the foreign key column(s).

@Entity
public class Contact ...

  // maps to "customer_id" foreign key column
  @ManyToOne
  Customer customer;
  ...

If the foreign key column does not match the naming convention based on the property name + "_id" then we need to define a @JoinColumn.

@Entity
public class Contact ...

  // explicit @JoinColumn of "cust_id" as the foreign key column
  @ManyToOne @JoinColumn("cust_id")
  Customer customer;
  ...

optional=false

If the underlying foreign key should have a NOT NULL constraint then we specify optional=false.

@Entity
public class Contact ...

  // not null constraint as optional=false
  @ManyToOne(optional=false)
  Customer customer;
  ...

@NotNull

We can use javax validation @NotNull instead of optional=false to define that the underlying foreign key column has a NOT NULL constraint.

@Entity
public class Contact ...

  // @NotNull same as optional=false
  @NotNull @ManyToOne
  Customer customer;
...