Video in progress

What does the @JoinColumn annotation do?

@JoinColumn defines the name and properties of the foreign key column: its name, nullability, and which column it references. If you leave it out, Hibernate builds the name itself in the form field_id.

📖 Answer

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "author_id", nullable = false,
            foreignKey = @ForeignKey(name = "fk_book_author"))
private Author author;

Here:

  • name is the column name in the books table;
  • nullable = false is for DDL generation;
  • optional = false tells Hibernate "this value is never null", and based on that it sometimes uses an inner join;
  • foreignKey is the constraint name in schema generation.

referencedColumnName is rarely needed: only when the foreign key points to a unique column of the other table rather than its primary key (for example, country_code).

@JoinColumn goes only on the owning side. Putting it on the mappedBy side makes no sense, and Hibernate throws an error.

One more case: @OneToMany + @JoinColumn (without mappedBy) is a "unidirectional one-to-many". The foreign key lives in the child table, but the parent side controls it.