JAVA-250 · Lesson 8 of 12 · 26 min
Entities, keys and relationships
▶ Video coming soon A video version of this lesson is on the way.
On Friday, November 12, Hamza and Ingrid mapped ShopBook's two main tables, bike and booking, as JPA entities. ShopBook was the natural place to try JPA: its code was full of objects that pointed at each other, a bike with its bookings and a booking with its bike, and most of its work was loading a few of them, changing them and saving them. By the end of the evening they had found every classic mistake in this lesson, including a booking that disappeared from a HashSet after it was saved. This lesson covers how JPA maps keys, how it generates them, how relationships between entities are mapped, and how cascades, orphan removal, versions and equality behave.
Primary keys: natural and surrogate
Every entity needs an identifier mapped to the table's primary key, marked with @Id. There are two kinds of key. A natural key is a value that already identifies the thing in the real world, such as a part code or a bike's fleet tag. A surrogate key is a meaningless number or UUID created only to be a key, such as booking.id. Natural keys are readable and avoid an extra column, but real-world values sometimes change or turn out not to be unique; if the shop ever renumbered its fleet tags, every booking row that pointed at a bike tag would have needed updating. Surrogate keys never change, which is why most JPA designs give every entity one and keep the natural value as a separate column with a UNIQUE constraint.
SELECT b.id, b.bike_tag, k.kind, b.customer, b.start_date
FROM booking b JOIN bike k ON k.tag = b.bike_tag
ORDER BY b.id;What this code does
ShopBook's current tables use the bike tag, a natural key, as the foreign key in booking. The join follows that key back to the bike.
| id | bike_tag | kind | customer | start_date |
|---|---|---|---|---|
| 1 | SG-0007-AR | CARGO | Ravi | 2027-10-02 |
| 2 | SG-0012-TA | TANDEM | Lin family | 2027-10-02 |
| 3 | SG-0003-CI | CITY | Mei | 2027-10-09 |
| 4 | SG-0007-AR | CARGO | Ana | 2027-10-16 |
| 5 | SG-0003-CI | CITY | Theo | 2027-10-16 |
For a surrogate key, the database or JPA must generate the value. @GeneratedValue chooses how, with four strategies. IDENTITY uses an auto-increment column: the database creates the value on INSERT, so the provider has to send the INSERT as soon as persist is called to learn the key, which prevents it from batching inserts. SEQUENCE uses a database sequence: the provider asks the sequence for values first, often fifty at a time with an allocation size, and can then batch inserts; it is the usual choice on PostgreSQL and Oracle. UUID, added in JPA 3.1, generates a java.util.UUID in Java. AUTO lets the provider choose; Hibernate picks SEQUENCE where the database supports it.
| Strategy | Key created by | INSERT sent | Typical use |
|---|---|---|---|
| IDENTITY | Auto-increment column | Immediately at persist | MySQL, SQL Server, SQLite |
| SEQUENCE | Database sequence, values fetched in blocks | At flush, can be batched | PostgreSQL, Oracle |
| UUID | Java, as a UUID | At flush | Keys created on several machines |
| TABLE | A table holding the next value | At flush | Rare; slow under load |
| AUTO | Provider decides | Depends | Default when no strategy is given |
The example below imitates a sequence with an allocation size of 50: one round trip to the database reserves a block of fifty numbers, and the provider hands them out from memory until the block runs out. That is how SEQUENCE saves round trips. The gaps it leaves after a restart are normal and harmless, because surrogate keys only have to be unique, not consecutive.
import java.util.*;
public class Main {
static class Sequence { // the database's sequence
private long next = 1;
int calls = 0;
long nextBlock(int size) { calls++; long start = next; next += size; return start; }
}
static class PooledGenerator { // the provider's side
private final Sequence seq; private final int allocationSize;
private long current = 0, limit = 0;
PooledGenerator(Sequence seq, int allocationSize) { this.seq = seq; this.allocationSize = allocationSize; }
long nextId() {
if (current == limit) { current = seq.nextBlock(allocationSize); limit = current + allocationSize; }
return current++;
}
}
public static void main(String[] args) {
Sequence seq = new Sequence();
PooledGenerator gen = new PooledGenerator(seq, 50);
List<Long> first = new ArrayList<>();
for (int i = 0; i < 120; i++) {
long id = gen.nextId();
if (i < 3 || i == 49 || i == 50 || i == 119) first.add(id);
}
System.out.println("Sample ids: " + first);
System.out.println("Round trips for 120 ids: " + seq.calls);
PooledGenerator afterRestart = new PooledGenerator(seq, 50); // program restarted
System.out.println("First id after restart: " + afterRestart.nextId());
}
}Sample ids: [1, 2, 3, 50, 51, 120] Round trips for 120 ids: 3 First id after restart: 151
What this code does
The first call reserves ids 1 to 50, the 51st id triggers a second block and the 101st a third, so 120 ids cost three round trips instead of 120. After the restart the generator does not know about ids 121 to 150, which the old block had reserved, so it starts a new block at 151. The gap is the price of fewer round trips and does no harm.
@Entity
@Table(name = "bike")
public class Bike {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "bike_seq")
@SequenceGenerator(name = "bike_seq", sequenceName = "bike_seq", allocationSize = 50)
private Long id;
@Column(nullable = false, unique = true)
private String tag; // the natural key, kept unique
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Kind kind;
protected Bike() {}
public Bike(String tag, Kind kind) { this.tag = tag; this.kind = kind; }
public Long getId() { return id; }
public String getTag() { return tag; }
}What this code does
The surrogate id comes from a sequence in blocks of 50, while the tag stays a unique column that people can read. EnumType.STRING stores the enum's name, such as CARGO; the default, ORDINAL, stores its position, which silently breaks if someone adds a new kind in the middle of the enum. The id is a Long rather than a long so that it can be null before the bike is saved.
Mapping relationships
A relationship between entities is a field whose type is another entity, or a collection of them, with an annotation saying how it is stored. JPA has four: @ManyToOne (many bookings for one bike), @OneToMany (one bike, many bookings), @OneToOne and @ManyToMany. In the database every one of them comes down to a foreign key: a column in the table on the many side, or, for many-to-many, a join table with two foreign keys. @JoinColumn names that column.
A relationship can be unidirectional, with a field on one side only, or bidirectional, with a field on each side. A bidirectional relationship still has only one foreign key, so JPA must be told which field controls it. That field is the owning side; for one-to-many it is always the @ManyToOne field on the many side, Booking.bike. The other side is the inverse side and says mappedBy, naming the owning field. The rule that follows surprises almost everyone once: JPA writes the foreign key only from the owning side. Adding a booking to bike.getBookings() without setting booking.bike saves nothing.
@Entity
@Table(name = "booking")
public class Booking {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false) // owning side
@JoinColumn(name = "bike_id")
private Bike bike;
private String customer;
private LocalDate startDate;
private LocalDate endDate;
@Version private int version;
// constructors, getters ...
}
// in Bike
@OneToMany(mappedBy = "bike", cascade = CascadeType.ALL, orphanRemoval = true) // inverse side
private List<Booking> bookings = new ArrayList<>();
public void addBooking(Booking b) { bookings.add(b); b.setBike(this); }
public void removeBooking(Booking b) { bookings.remove(b); b.setBike(null); }What this code does
Booking.bike is the owning side and maps the bike_id column; Bike.bookings says mappedBy = "bike", so it is read from that column but never written. The helper methods addBooking and removeBooking keep both sides in step, so the Java objects and the database always agree. LAZY on the many-to-one is explained in lesson 10, and @Version is explained later in this lesson.
Why do the helper methods matter if JPA only reads the owning side? Because until the next load, your program sees only the Java objects. If a booking's bike is set but the bike's list is not updated, the database will be right after the flush, but code in the same unit of work that looks at bike.getBookings() will not see the new booking. The example below shows the two kinds of drift and how the helpers prevent both.
import java.util.*;
public class Main {
static class Bike {
final String tag; final List<Booking> bookings = new ArrayList<>();
Bike(String tag) { this.tag = tag; }
void addBooking(Booking b) { bookings.add(b); b.bike = this; }
void removeBooking(Booking b) { bookings.remove(b); b.bike = null; }
}
static class Booking {
final String customer; Bike bike;
Booking(String customer) { this.customer = customer; }
}
// what JPA writes: the owning side only
static String foreignKey(Booking b) { return b.bike == null ? "NULL" : b.bike.tag; }
static List<String> list(Bike b) { return b.bookings.stream().map(k -> k.customer).toList(); }
public static void main(String[] args) {
Bike cargo = new Bike("SG-0007-AR");
Booking ravi = new Booking("Ravi");
cargo.bookings.add(ravi); // inverse side only
System.out.println("Ravi: list " + list(cargo) + ", bike_id " + foreignKey(ravi));
Booking ana = new Booking("Ana");
ana.bike = cargo; // owning side only
System.out.println("Ana: list " + list(cargo) + ", bike_id " + foreignKey(ana));
Bike tandem = new Bike("SG-0012-TA");
Booking lin = new Booking("Lin family");
tandem.addBooking(lin); // helper: both sides
System.out.println("Lin: list " + list(tandem) + ", bike_id " + foreignKey(lin));
tandem.removeBooking(lin);
System.out.println("Lin removed: list " + list(tandem) + ", bike_id " + foreignKey(lin));
}
}Ravi: list [Ravi], bike_id NULL Ana: list [Ravi], bike_id SG-0007-AR Lin: list [Lin family], bike_id SG-0012-TA Lin removed: list [], bike_id NULL
What this code does
Ravi appears in the bike's list, but his foreign key is NULL, so JPA would save his booking without a bike, or fail because the column is NOT NULL. Ana has the right foreign key but is missing from the list, so code in the same unit of work would not see her booking. The helper methods change both sides together, so the list and the foreign key always agree.
Cascades and orphan removal
By default, JPA operations apply only to the entity you pass. Cascading passes them along a relationship: with cascade = CascadeType.PERSIST on Bike.bookings, persisting a new bike also persists the new bookings in its list. CascadeType.ALL cascades persist, merge, remove, refresh and detach. Cascades belong on relationships where the parent owns the children's life cycle, such as an order and its lines. They do not belong on a many-to-one: cascading remove from a booking to its bike would delete the bike, and every other booking with it, when one booking is cancelled.
orphanRemoval = true goes one step further: a child removed from the parent's collection is deleted from the database at flush, even though nobody called remove on it. It suits children that cannot exist without their parent. Whether bookings are such children is a business decision, not a technical one. Ingrid pointed out that the shop needs cancelled bookings for its records, so in ShopBook a cancelled booking is marked with a status instead, and orphanRemoval stays off.
| Setting | What happens | Use when |
|---|---|---|
| No cascade | Each entity must be persisted and removed on its own | The default; independent entities |
| cascade = PERSIST | New children are inserted with the parent | Children created together with the parent |
| cascade = ALL | All operations pass to the children, including remove | Parent owns the children completely |
| orphanRemoval = true | Children removed from the collection are deleted | Children cannot exist without the parent |
| Cascade on @ManyToOne | Operations pass from child to parent | Almost never |
Optimistic locking with @Version
Lesson 4 showed the lost update: two people read the same row, both change it, and the second write silently overwrites the first. JPA's answer is optimistic locking. Give the entity a field marked @Version. Every UPDATE then includes the version in its WHERE clause and increments it: UPDATE booking SET ..., version = 4 WHERE id = 5 AND version = 3. If someone else has changed the row in the meantime, the version no longer matches, no row is updated, and the provider throws an OptimisticLockException, which the program can report or retry. Nothing is locked while users think, which is why it is called optimistic.
CREATE TABLE booking_versioned (id INTEGER PRIMARY KEY, customer TEXT, end_date TEXT, version INTEGER NOT NULL);
INSERT INTO booking_versioned VALUES (5, 'Theo', '2027-10-17', 3);
-- Hamza extends the booking, holding version 3
UPDATE booking_versioned SET end_date = '2027-10-18', version = 4 WHERE id = 5 AND version = 3;
SELECT changes() AS hamza_rows;
-- Odile, also holding version 3, tries to shorten it
UPDATE booking_versioned SET end_date = '2027-10-16', version = 4 WHERE id = 5 AND version = 3;
SELECT changes() AS odile_rows;What this code does
The statements a provider sends for a versioned entity, run in SQLite. Hamza's update matches version 3 and changes one row; Odile's still says version 3, matches nothing and changes zero rows, which is the signal Hibernate turns into an OptimisticLockException. The booking keeps Hamza's end date.
| id | customer | end_date | version |
|---|---|---|---|
| 5 | Theo | 2027-10-18 | 4 |
Equality of entities
Entities live in HashSets and as HashMap keys, so equals and hashCode matter. The tempting choices are wrong. The default from Object compares identity, which is fine inside one persistence context but fails when comparing objects from two contexts. Comparing every field breaks as soon as a field changes. And comparing the generated id has a subtle trap: the id is null until the entity is persisted, so an object put into a HashSet before saving changes its hash code when the id arrives, and the set can no longer find it. That is exactly the booking Hamza lost.
import java.util.*;
public class Main {
static long nextId = 41;
static class Booking { // equality by generated id: the trap
Long id; final String customer;
Booking(String customer) { this.customer = customer; }
@Override public boolean equals(Object o) { return o instanceof Booking b && Objects.equals(id, b.id); }
@Override public int hashCode() { return Objects.hashCode(id); }
}
static class SafeBooking { // equal only if both have the same non-null id
Long id; final String customer;
SafeBooking(String customer) { this.customer = customer; }
@Override public boolean equals(Object o) {
return o instanceof SafeBooking b && id != null && id.equals(b.id);
}
@Override public int hashCode() { return SafeBooking.class.hashCode(); } // constant, never changes
}
public static void main(String[] args) {
Set<Booking> bookings = new HashSet<>();
Booking theo = new Booking("Theo");
bookings.add(theo);
theo.id = nextId++; // persist assigns the id
System.out.println("Trap: contains=" + bookings.contains(theo) + ", remove=" + bookings.remove(theo) + ", size=" + bookings.size());
Booking a = new Booking("Ana"), b = new Booking("Mei");
System.out.println("Two unsaved bookings equal: " + a.equals(b));
Set<SafeBooking> safe = new HashSet<>();
SafeBooking t2 = new SafeBooking("Theo");
safe.add(t2);
t2.id = nextId++;
System.out.println("Safe: contains=" + safe.contains(t2) + ", remove=" + safe.remove(t2) + ", size=" + safe.size());
System.out.println("Two unsaved safe bookings equal: " + new SafeBooking("Ana").equals(new SafeBooking("Mei")));
}
}Trap: contains=false, remove=false, size=1 Two unsaved bookings equal: true Safe: contains=true, remove=true, size=0 Two unsaved safe bookings equal: false
What this code does
After the id is assigned, theo's hash code changes, so the set looks in the wrong bucket: contains and remove both fail and the booking is stuck in the set. The same equals also makes any two unsaved bookings equal, because both ids are null. The safe version treats unsaved entities as different and uses a constant hash code, which never changes, at the cost of putting every booking in one bucket, an acceptable price for the small sets entities usually live in.
There are two widely recommended answers. If the entity has a natural key that never changes and is set in the constructor, such as a part code, use it for equals and hashCode; that is also a good reason to keep natural keys as unique columns even when a surrogate is the primary key. Otherwise use the pattern above: equal only when both ids are non-null and equal, with a constant hash code. Whichever you choose, never include relationship fields: comparing a bike's bookings and each booking's bike would recurse forever, and with lazy loading it would also load half the database.
Try it yourself
Keep both sides in sync
Complete addBooking so that it adds the booking to the bike's list and sets the booking's bike field.
The program prints [Ravi, Ana] and SG-0007-AR SG-0007-AR.
import java.util.*;
public class Main {
static class Bike {
final String tag; final List<Booking> bookings = new ArrayList<>();
Bike(String tag) { this.tag = tag; }
void addBooking(Booking b) {
bookings.add(b);
}
}
static class Booking {
final String customer; Bike bike;
Booking(String customer) { this.customer = customer; }
}
public static void main(String[] args) {
Bike cargo = new Bike("SG-0007-AR");
Booking ravi = new Booking("Ravi"), ana = new Booking("Ana");
cargo.addBooking(ravi);
cargo.addBooking(ana);
System.out.println(cargo.bookings.stream().map(b -> b.customer).toList());
System.out.println((ravi.bike == null ? "null" : ravi.bike.tag) + " " + (ana.bike == null ? "null" : ana.bike.tag));
}
}Try it yourself
Equality by natural key
Write equals and hashCode for Part using only the code field.
The program prints true, 1 and true.
import java.util.*;
public class Main {
static class Part {
final String code; int quantity;
Part(String code, int quantity) { this.code = code; this.quantity = quantity; }
}
public static void main(String[] args) {
Part a = new Part("BELL", 3), b = new Part("BELL", 7);
System.out.println(a.equals(b));
Set<Part> set = new HashSet<>(List.of(a));
set.add(b);
System.out.println(set.size());
a.quantity = 99;
System.out.println(set.contains(a));
}
}Common mistakes
MistakeAdding a child to the parent's collection without setting the child's reference.
InsteadSet the owning side, ideally through a helper that updates both sides.
MistakePutting mappedBy on the @ManyToOne side.
InsteadmappedBy goes on the inverse side, the @OneToMany, naming the owning field.
MistakeCascading remove from a booking to its bike.
InsteadCascade only from a parent to children whose life cycle it owns.
MistakeUsing EnumType.ORDINAL for enums.
InsteadUse EnumType.STRING so adding a constant cannot change stored meanings.
MistakeBasing hashCode on a generated id.
InsteadUse an immutable natural key, or a constant hash code with id-based equals.
Summary and key terms
- Every entity has an @Id.
- Natural keys come from the real world and can change; surrogate keys are generated and never change, so most designs use a surrogate primary key and keep the natural value unique. @GeneratedValue chooses IDENTITY, SEQUENCE, UUID, TABLE or AUTO; IDENTITY forces an immediate INSERT, while SEQUENCE with an allocation size saves round trips and allows batching, leaving harmless gaps.
- Relationships are @ManyToOne, @OneToMany, @OneToOne and @ManyToMany, each stored as a foreign key or join table.
- In a bidirectional relationship the owning side, the @ManyToOne, writes the foreign key and the inverse side says mappedBy; helper methods keep both sides in step.
- Cascades pass operations from parent to children, and orphanRemoval deletes children removed from a collection. @Version gives optimistic locking: updates check and increment the version, and a mismatch throws OptimisticLockException.
- Entity equality should use an immutable natural key, or id-based equals with a constant hash code, and never relationship fields.
- Natural key
- A key made of values that identify the thing in the real world.
- Surrogate key
- A generated key with no meaning outside the database.
- @GeneratedValue
- The annotation that chooses how primary key values are generated.
- Allocation size
- How many sequence values the provider reserves in one round trip.
- Owning side
- The side of a relationship whose field JPA uses to write the foreign key.
- Inverse side
- The side marked mappedBy, read from the foreign key but never writing it.
- mappedBy
- The attribute that names the owning field on the other entity.
- Cascade
- Passing an EntityManager operation along a relationship to related entities.
- Orphan removal
- Deleting a child entity when it is removed from its parent's collection.
- Optimistic locking
- Detecting conflicting updates with a version column instead of holding locks.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why is IDENTITY generation incompatible with insert batching?
Show answer
The provider must send each INSERT at once to learn the generated key.
In the Bike–Booking relationship, which side owns the foreign key?
Show answer
Booking.bike, the @ManyToOne side.
What does an update of a versioned entity add to its WHERE clause?
Show answer
AND version = the version that was read.
Why not base hashCode on a generated id?
Show answer
The id changes from null when the entity is saved, so hash-based collections lose it.
Should cancelling a ShopBook booking cascade to its bike?
Show answer
No; cascades go from parent to owned children, never from a booking to its bike.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.