ORM and JPA: entity relationships, owning sides and mappedBy
Mapping one-to-one, one-to-many and many-to-many in JPA: where the foreign key goes, owning sides and mappedBy, @MapsId, cascades and orphanRemoval, Set instead of List for @ManyToMany, and when a join table needs its own entity.
On this page
1. The problem
An admin deletes the account of a teacher who left. DELETE /teachers/7 returns 204 and takes 12 courses and 3,400 student enrolments with it. There's no delete call for courses anywhere: just cascade = ALL on an entity.
2. Key idea
An FK is like the owner's name on a vehicle registration. The list of cars in the owner's notebook (mappedBy) is for lookup only: adding a car to the notebook doesn't change the registration. EF Core, Django ORM and Prisma all make you name the FK column and all offer cascading deletes.
Before writing annotations, answer three questions:
- Where is the FK? That decides the owning side: the "many" side for 1-n, the dependent table with
UNIQUEfor 1-1, the join table for n-n. - Can the child live without the parent? That decides cascading: an
OrderLinecan't live without itsOrder, but aCoursestill has value when its teacher leaves. - Which direction do you need? Start with a one-way
@ManyToOne, add the collection when a real screen needs it.
| Choice | Use when | Don't use when |
|---|---|---|
One-way @ManyToOne |
the default for every 1-n | |
Add @OneToMany(mappedBy) |
you navigate parent to child, small collections | tens of thousands of children: use a paged query |
cascade = ALL + orphanRemoval |
composition: Order-OrderLine |
independently living data: Teacher-Course |
@OneToOne + @MapsId |
the dependent table shares the main table's PK | the two tables have separate lifecycles |
@ManyToMany + Set |
the join table has only two FK columns | you need extra columns: enrolment date, score |
A List @ManyToMany is a "bag": removing 1 tag issues 1 DELETE then reinserts every remaining row. The inverse side of a @OneToOne can't be lazy without bytecode enhancement.
3. In Java
The owning side carries the column; a helper keeps both directions in sync.
@Entity
public class Course {
@ManyToOne(fetch = FetchType.LAZY, optional = false) // EAGER by default: make it LAZY
@JoinColumn(name = "teacher_id", nullable = false) // owning side: holds the FK
private Teacher teacher;
}
@Entity
public class Teacher {
@OneToMany(mappedBy = "teacher", // field name, not column name
cascade = {CascadeType.PERSIST, CascadeType.MERGE}) // no REMOVE
private List<Course> courses = new ArrayList<>();
public void addCourse(Course c) {
courses.add(c);
c.setTeacher(this); // writes the owning side, or the FK stays null
}
}Other languages: EF Core HasOne().WithMany().HasForeignKey() with OnDelete(DeleteBehavior.Restrict); Django ForeignKey(on_delete=models.PROTECT).
Cascade, orphanRemoval and n-n in detail
cascadepropagatesEntityManageroperations (persist, merge, remove) from parent to child.orphanRemoval = truedeletes a child when it's removed from the parent's collection: only right for composition.- Never cascade
REMOVEon@ManyToMany: deleting one course would delete tags other courses still use. - A one-way
@OneToManywithout@JoinColumnmakes Hibernate create an extra join table. @OneToOnewith@MapsId:UserProfilesharesUser's PK, needs no separate FK column, and the child side can be lazy.- At the DB level, add
ON DELETE RESTRICTto important FKs: if a wrong cascade slips into code, the DB still refuses.
4. Working with AI
AI tends to copy cascade = CascadeType.ALL, List for n-n, and FetchType.EAGER.
Hand to AI: generating entities from SQL migrations, add…/remove… helpers, integration tests that save and reread from the DB.
Check in AI-written code:
- Each
@JoinColumnmatches the FK column in the migration;mappedBynames the right field on the other side. - Bidirectional relationships have a helper that updates the owning side.
-
@ManyToOneand@OneToOnehavefetch = FetchType.LAZY. - No
REMOVE/ALLon@ManyToManyor on relationships whose children live independently. -
@ManyToManyusesSet; a join table with a third column is its own entity.
5. Exercises
Exercise 1: Review a course import method
The AI wrote this, saying "cascade PERSIST takes care of saving the courses". A test counts teacher.getCourses().size() and sees 3. Find the bug, name a test that proves it, fix it.
@Transactional
public void importCourses(long teacherId, List<String> titles) {
Teacher t = teacherRepository.findById(teacherId).orElseThrow();
for (String title : titles) {
t.getCourses().add(new Course(title)); // Teacher.courses has mappedBy = "teacher"
}
}Solution to Exercise 1
It only adds to the mappedBy side. Cascade PERSIST still inserts the courses rows, but Hibernate doesn't look at this collection to write the FK, so teacher_id is null: an error on flush if the column is NOT NULL, otherwise silently orphaned courses.
That test passes because it reads the in-memory collection. The right test: flush(), clear(), then query courses by teacher_id from the DB.
Fix: t.addCourse(new Course(title)); set nullable = false and NOT NULL in the migration so the bug shows early.
Exercise 2: Read a cascading-delete incident
After a deploy, "delete departed teacher" ran once in production. The SQL log: delete from enrollments 3,400 times, delete from courses 12 times, delete from teachers once. The deployed diff added cascade = CascadeType.ALL on Teacher.courses; Course.enrollments already had cascade = ALL. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: cascade
REMOVE(part ofALL) propagated two levels,Teacher→Course→Enrollment. Hibernate deletes children row by row first to avoid FK violations. - 15 minutes: disable the delete feature (feature flag or rollback); restore the three tables from a backup or point-in-time recovery into a temporary schema, then copy back exactly the deleted rows.
- Root fix:
Teacher.coursescascades onlyPERSIST/MERGE; departed teachers are soft-deleted and their courses reassigned. AddON DELETE RESTRICTon the FK, and a test asserting that deleting a teacher with courses fails.
Summary
- The FK lives in one table; the owning side holds it,
mappedByis read only. - Changing only the
mappedByside leaves the FKnull: use a two-way helper. - Every relationship is LAZY.
- Cascade
ALLandorphanRemovalonly for composition, never for@ManyToMany. - n-n uses a
Set; extra columns mean a separate entity.
Read more: Part 3: The E-Learning schema, DTOs, JSON.
Next up: ORM and JPA part 3: mapping the E-Learning schema, DTOs and JSON recursion.
Practice interview questions on this topic
- What is the owning side of a JPA relationship, and what is mappedBy for?
- How do CascadeType.REMOVE and orphanRemoval differ?
- When do you use @ManyToMany, and when do you promote the join table to its own entity?
- What inheritance strategies does JPA offer, and how does @MappedSuperclass differ?
- How do FetchType LAZY and EAGER differ, and what should the default be?
- What are @Entity, @Id and @GeneratedValue for? Should you pick IDENTITY, SEQUENCE, UUID or AUTO?
Comments
Community rules