A primary key identifies a database row by its column value or combination of column values. For a persistent entity, the database identifier maps to the table’s primary key. This is database identity, not necessarily Java instance identity (`==`) or object equality (`equals()`): distinct Java objects can represent the same row. section 5.2.3 section 1.2.3
Choose a key that remains reliable throughout the row’s lifetime:
- Require a non-null, unique value. A composite key can use several columns; a candidate key should not include columns unnecessary for uniqueness. section 5.2.3
- Keep the primary-key value unchanged. Hibernate and Spring Data JPA with Hibernate as provider do not support updating it through their API; workarounds can disrupt caching and dirty checking. section 5.2.3
- Consider a surrogate key when no suitable natural key exists. Keep another genuinely unique candidate key under a database unique constraint. section 1.2.3 section 5.2.3
CREATE TABLE USERS (
ID BIGINT NOT NULL PRIMARY KEY,
USERNAME VARCHAR(15) NOT NULL UNIQUE,
. . .
);
CREATE TABLE BILLINGDETAILS (
ID BIGINT NOT NULL PRIMARY KEY,
ACCOUNT VARCHAR(15) NOT NULL,
BANKNAME VARCHAR(255) NOT NULL,
USER_ID BIGINT NOT NULL,
FOREIGN KEY (USER_ID) REFERENCES USERS(ID)
);
Compare the generated `USERS.ID` primary key with the still-unique `USERNAME`: `BILLINGDETAILS.USER_ID` references the stable identifier rather than a username that might change. section 1.2.3
The table structure also determines which values need independent keys. An embedded `Address` shares its owning `User` row and identifier; it has no separate identity or lifecycle. For a set of embedded images, the collection table instead uses a composite primary key: `ITEM_ID` plus the non-null embedded columns `FNAME`, `WIDTH`, and `HEIGHT`. Including `ITEM_ID` distinguishes otherwise equal images belonging to different items. section 6.2.1 section 8.2.2




















