Skip to content
notes.vinhnq.com

Search

Database & ORMMid12 min read

ORM and JPA: entity relationships, owning sides and mappedBy

Review 12 cards
On this page

ORM and JPA series: 1. Entities and repositories · 2. Entity relationships · 3. The E-Learning schema, DTOs, JSON · 4. Persistence context and N+1 · 5. JPQL, @Transactional, locking

Part 1 built entities for individual tables; in this part they start pointing at each other. Afterwards you’ll know where the foreign key goes, which entity is the owning side, what mappedBy really means and how far a cascade can safely reach. Read part 1 and the ERD and foreign key material in the Databases series first.

1. Relationships between entities

Key idea: relationships in Java must match the foreign keys in the database; JPA needs to know which side holds the FK so it can write that column.

After this: part 3 applies these mappings to the course’s real E-Learning schema and deals with JSON recursion, part 4 covers the persistence context and N+1, and part 5 covers JPQL, @Transactional and locking.

1.1. Entities, attributes, relationships

Key idea: an entity is something to store (Teacher, Course), attributes are its properties (id, name), and a relationship links entities. There are three kinds.

  • One-to-One (1-1): each student borrows only one book, and each book is lent to one student.
  • One-to-Many (1-n): each student can borrow many books.
  • Many-to-Many (n-n): a student attends many classes, and a class has many students.

1.2. How a relational database represents them

Key idea: tables are linked by foreign keys (FK — a column pointing at another table’s primary key; the database won’t let it point at a row that doesn’t exist). The kind of relationship decides where the FK goes.

Relationship Where the FK goes Why
1-1 the dependent table (the one that can’t exist on its own), plus UNIQUE without UNIQUE two rows can point at the same parent, and you’ve built a 1-n by accident
1-n must be on the “many” side (each book stores student_id) on the “one” side a cell would hold several values, breaking first normal form
n-n a join table with two FK columns the pair usually forms the join table’s primary key

The trimmed-down model used in this post (the full schema, with chapters, lessons, progress and addresses, is in part 3):

erDiagram
  USERS ||--|| USER_PROFILES : has
  TEACHERS ||--o{ COURSES : teaches
  STUDENTS ||--o{ ENROLLMENTS : makes
  COURSES ||--o{ ENROLLMENTS : has
  COURSES }o--o{ TAGS : labeled_with

  USERS {
    bigint id PK
    varchar username
  }
  USER_PROFILES {
    bigint user_id PK,FK
    varchar full_name
  }
  TEACHERS {
    bigint id PK
    varchar name
  }
  COURSES {
    bigint id PK
    bigint teacher_id FK
    varchar title
  }
  STUDENTS {
    bigint id PK
    varchar name
  }
  ENROLLMENTS {
    bigint id PK
    bigint student_id FK
    bigint course_id FK
    datetime enrolled_at
  }
  TAGS {
    bigint id PK
    varchar name
  }

Student-Course is fundamentally many-to-many, but it needs extra data (enrolment date, payment, progress), so the join table becomes its own entity, Enrollment (what most real systems do).

1.3. Owning side and mappedBy (the slides get this backwards)

Key idea: the owning side is the entity holding the FK (with @JoinColumn, or @JoinTable for many-to-many); Hibernate only looks at this side when writing the FK column. The side declaring mappedBy is the inverse side, there purely for navigation in Java.

The value of mappedBy is the Java field name on the other entity, not a column name.

1.4. One-to-one

Key idea: put @OneToOne + @JoinColumn on the dependent table (UserProfile) and mappedBy on the main one (User). Use @MapsId so the profile shares the user’s primary key.

Example: each User has exactly one UserProfile (full name, date of birth).

@Entity
@Table(name = "users")
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private UserProfile profile;

    public void setProfile(UserProfile profile) { // keep both sides in sync
        this.profile = profile;
        profile.setUser(this);
    }
}

@Entity
@Table(name = "user_profiles")
public class UserProfile {
    @Id
    private Long id; // same value as users.id

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "user_id")
    private User user;

    private String fullName;
}
  • @JoinColumn(name = "user_id") on UserProfile: the owning side, holding the FK to users. mappedBy = "user" on User: the inverse side.
  • CascadeType.ALL: every operation on User propagates to UserProfile, which is reasonable because the profile belongs to the user.
  • The slides use FetchType.EAGER. EAGER is indeed the default for @OneToOne and @ManyToOne, but you should always set LAZY and fetch when needed (see part 4 of the series).
  • Senior tip: with @MapsId, user_profiles.user_id is both PK and FK: no separate id column or index, and you look up a profile with findById(userId).
Why the inverse side of a @OneToOne is still loaded eagerly

1.5. One-to-many

Key idea: @ManyToOne + @JoinColumn on the “many” side is always the owning side; @OneToMany(mappedBy) goes on the “one” side. The addCourse helper writes both sides so the FK isn’t null.

Example: a Teacher teaches many Courses. The FK teacher_id lives in courses.

@Entity
public class Teacher {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "teacher", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Course> courses = new ArrayList<>();

    public void addCourse(Course course) {
        courses.add(course);
        course.setTeacher(this); // write the owning side, or the FK stays null
    }

    public void removeCourse(Course course) {
        courses.remove(course);
        course.setTeacher(null);
    }
}

@Entity
public class Course {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "teacher_id", nullable = false)
    private Teacher teacher;
}
  • @OneToMany is LAZY by default: courses is only queried when you touch it (teacher.getCourses().size()).
  • orphanRemoval = true is not the same as CascadeType.REMOVE: it deletes a child once it’s removed from the collection; REMOVE deletes children only when the parent is deleted. Use it for true composition (Order and OrderLine).
The unidirectional @OneToMany without @JoinColumn trap

Avoid a unidirectional @OneToMany without @JoinColumn: Hibernate then creates a teacher_courses join table as if it were many-to-many, with an extra table and extra SQL. If you only need one direction, pick @ManyToOne.

1.6. Many-to-many

Key idea: the owning side gets @ManyToMany + @JoinTable, the other side mappedBy. Use a Set, never cascade removals, and promote the join table to an entity once it needs extra columns.

The slides use User - Address (a person lives at many addresses, an address houses many people); the pet project uses Course - Tag.

@Entity
public class Course {
    // ...
    @ManyToMany
    @JoinTable(
        name = "course_tags",
        joinColumns = @JoinColumn(name = "course_id"),        // FK to this entity
        inverseJoinColumns = @JoinColumn(name = "tag_id"))    // FK to the other entity
    private Set<Tag> tags = new HashSet<>();

    public void addTag(Tag tag) { tags.add(tag); tag.getCourses().add(this); }
    public void removeTag(Tag tag) { tags.remove(tag); tag.getCourses().remove(this); }
}

@Entity
public class Tag {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String name;

    @ManyToMany(mappedBy = "tags")
    private Set<Course> courses = new HashSet<>();
}
  • @JoinTable: name is the join table, joinColumns is the FK back to the entity declaring @JoinTable, inverseJoinColumns is the FK to the other entity.
  • Never cascade REMOVE/ALL on @ManyToMany: deleting a course would delete tags that other courses still use.
The Enrollment join entity code
@Entity
@Table(name = "enrollments",
       uniqueConstraints = @UniqueConstraint(columnNames = {"student_id", "course_id"}))
public class Enrollment {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "student_id")
    private Student student;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "course_id")
    private Course course;

    private Instant enrolledAt;
}

1.7. Cheat sheet

Key idea: the owning side is always the one carrying column information (@JoinColumn, @MapsId, @JoinTable); the inverse side is always mappedBy.

Annotation Owning side has Inverse side has Default fetch
@OneToOne @JoinColumn (or @MapsId) mappedBy EAGER
@ManyToOne / @OneToMany @ManyToOne + @JoinColumn @OneToMany(mappedBy) EAGER / LAZY
@ManyToMany @JoinTable(joinColumns, inverseJoinColumns) mappedBy LAZY

Exercises

This lesson’s relationship-mapping exercise works on the full E-Learning schema, so its solution lives in part 3, Exercise 4. The exercises on entities, repositories and CRUD are in part 1.

Further reading from the slides

Three topics the slides suggest reading up on

The slides suggest reading up on entity relationships (section 1), Spring filters (servlet filters that run before the DispatcherServlet, used for logging, trace ids and authentication) and Dependency Injection (see IoC and Dependency Injection).

Remember

  • Can you say where the FK goes for 1-1, 1-n and n-n, and why 1-1 needs UNIQUE?
  • Can you explain why teacher.getCourses().add(course) alone leaves teacher_id as null?
  • Do you know when cascade ALL/orphanRemoval is safe, and when it deletes data by mistake?
  • Can you explain why @ManyToMany should use a Set, and when to promote it to a join entity?

Interview questions

Junior

In a one-to-many relationship, where does the foreign key go and why?

On the “many” table (each course stores teacher_id).

On the “one” side a single cell would have to hold many values, which breaks first normal form. In JPA the @ManyToOne side holds the FK and is the owning side.

What is mappedBy for?

It marks the inverse side of a bidirectional relationship; its value is the field name on the other entity.

The mappedBy side holds no FK, and changes made only there aren’t written to the database. Hibernate relies solely on the owning side (the one with @JoinColumn/@JoinTable).

What does a unidirectional @OneToMany without @JoinColumn produce?

An extra join table (e.g. teacher_courses), because Hibernate treats it like a many-to-many.

Every child you add means another INSERT into that table, even though the business only needs a teacher_id column on the child table. If you need only one direction, map @ManyToOne on the child; if you need both, add @OneToMany(mappedBy = ...) on the parent.

Mid

How do CascadeType.REMOVE and orphanRemoval differ?

REMOVE deletes children when the parent is deleted; orphanRemoval deletes a child when it’s removed from the parent’s collection, even if the parent lives on.

Both only make sense for true ownership, and never on @ManyToMany.

Why use a Set instead of a List for @ManyToMany?

Because a List without an order column is a bag: removing one element makes Hibernate delete all of that entity’s rows in the join table and re-insert the rest.

A Set lets it delete exactly one row. Fetch-joining two bags at once also throws MultipleBagFetchException.

When do you use @ManyToMany, and when do you turn the join table into its own entity?

@ManyToMany when the join table holds only the two FK columns; once the relationship needs attributes of its own, make it an entity.

Two-column examples: course–tag, user–address. With an enrolment date, grade, status or rating it must be a separate entity with two @ManyToOnes and a unique constraint on the FK pair. Many teams default to a separate entity from day one, because relationships tend to grow columns.

Senior

Why is the inverse side of a @OneToOne loaded eagerly even when marked LAZY?

Because to create a proxy Hibernate must know whether the association is null, and the inverse side has no FK column, so it has to query the other table.

The owning side has an FK column, so it knows immediately. Workarounds: use @MapsId and map only the child-to-parent direction, enable bytecode enhancement, or replace the association with an explicit query when needed.

Useful phrases for interviews

  • “The owning side is the one with the foreign key; mappedBy just marks the inverse side for navigation.”
  • “I default every association to LAZY and decide what to fetch per use case.”
  • “I’d rather not cascade removals here, because deleting a teacher shouldn’t wipe out course history.”
  • “Since the profile shares the user’s primary key through @MapsId, there’s no extra column or index to maintain.”
  • “As soon as the join table needed a rating column, we promoted it to an entity with two many-to-one associations.”
  • “A unidirectional many-to-one is usually all you need; I add the collection side only when navigation really needs it.”
  • “Cascade ALL with orphan removal only makes sense for true composition, like an order and its lines.”
  • “I use a Set for many-to-many, otherwise Hibernate rewrites the whole join table on every removal.”

Next up: ORM and JPA part 3: mapping the E-Learning schema, DTOs and JSON recursion.


Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.