SteelReed

Search

Search posts, questions…

4. Database & SQL

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.

17 Nov 20267 min readMid

–

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 UNIQUE for 1-1, the join table for n-n.
  • Can the child live without the parent? That decides cascading: an OrderLine can't live without its Order, but a Course still 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.

JAVA
@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
  • cascade propagates EntityManager operations (persist, merge, remove) from parent to child. orphanRemoval = true deletes a child when it's removed from the parent's collection: only right for composition.
  • Never cascade REMOVE on @ManyToMany: deleting one course would delete tags other courses still use.
  • A one-way @OneToMany without @JoinColumn makes Hibernate create an extra join table.
  • @OneToOne with @MapsId: UserProfile shares User's PK, needs no separate FK column, and the child side can be lazy.
  • At the DB level, add ON DELETE RESTRICT to 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 @JoinColumn matches the FK column in the migration; mappedBy names the right field on the other side.
  • Bidirectional relationships have a helper that updates the owning side.
  • @ManyToOne and @OneToOne have fetch = FetchType.LAZY.
  • No REMOVE/ALL on @ManyToMany or on relationships whose children live independently.
  • @ManyToMany uses Set; 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.

JAVA
@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 of ALL) 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.courses cascades only PERSIST/MERGE; departed teachers are soft-deleted and their courses reassigned. Add ON DELETE RESTRICT on 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, mappedBy is read only.
  • Changing only the mappedBy side leaves the FK null: use a two-way helper.
  • Every relationship is LAZY.
  • Cascade ALL and orphanRemoval only 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

All JPA & Hibernate questions →

Loading comments…