liveBook · Manning

Foreign key

As explained in Java Persistence with Spring Data and Hibernate epub

A foreign key constraint enforces a referential relationship between values in one table and a candidate or primary key in another table.

A foreign key constraint enforces a referential relationship between values in one table and a candidate or primary key in another. In relational schemas, it represents an association through copied key values rather than object references. section 1.2.4

Linking billing details to a user

A billing-details table can require every USERNAME to identify an existing user: CREATE TABLE BILLINGDETAILS ( ACCOUNT VARCHAR(15) NOT NULL PRIMARY KEY, BANKNAME VARCHAR(255) NOT NULL, USERNAME VARCHAR(15) NOT NULL, FOREIGN KEY (USERNAME) REFERENCES USERS(USERNAME) ); This models a many-to-one association: each billing account belongs to one user, while a user may have several accounts. section 1.2 section 1.2.4

Foreign keys shape relational representations of associations in several ways:

  • Use a single foreign key for a many-to-one association, such as multiple billing accounts referencing one user. section 1.2.4
  • Introduce a link table for a many-to-many association, with foreign keys referencing both participating tables. section 1.2.4
  • Recognize that a foreign key targets exactly one table, so it cannot directly represent a polymorphic association spanning multiple subclass tables. section 1.2.2
CREATE TABLE USERS (
    USERNAME VARCHAR(15) NOT NULL PRIMARY KEY,
    ADDRESS VARCHAR(255) NOT NULL
);
 
CREATE TABLE BILLINGDETAILS (
    ACCOUNT VARCHAR(15) NOT NULL PRIMARY KEY,
    BANKNAME VARCHAR(255) NOT NULL,
    USERNAME VARCHAR(15) NOT NULL,
    FOREIGN KEY (USERNAME) REFERENCES USERS(USERNAME)
);

Inspect the complete USERS and BILLINGDETAILS schema, including the foreign key declaration. section 1.2

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Defines the constraint, demonstrates SQL syntax, compares association cardinalities, and stops short of ORM inheritance solutions.
Examples
Uses User and BillingDetails tables, a USER_BILLINGDETAILS link table, and an IMAGE table referencing ITEM.
What it assumes
Builds from Java entity associations and SQL tables while contrasting object navigation with relational key values.
What you can do after
Apply it via SQL to preserve associations and choose schemas for one-to-many or many-to-many relationships.
How it connects
Connects relational tables with primary keys, object references, associations, inheritance, and link tables.

Also explained in

Compare how 18 books explain foreign key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.