JPA
Hibernate
mappedBy
Java
ORM

mappedBy in JPA and Hibernate explained

Codemia Knowledge Hub ·

In JPA and Hibernate, mappedBy declares the inverse (non-owning) side of a bidirectional relationship. It tells the persistence provider "the foreign key lives on the other entity, in the field named by this string." Without mappedBy, Hibernate assumes both sides own the relationship and creates a redundant join table. The entity without mappedBy (the one with @JoinColumn) is the owning side, and only it controls inserts and updates to the foreign key column.

Owning side vs. inverse side

Every bidirectional relationship has exactly two sides:

Owning side: the entity whose table holds the foreign key column. It has @JoinColumn (or is the default owner in @ManyToMany). Changes to its collection or reference are written to the database.

Inverse side: the entity that declares mappedBy. The persistence provider treats it as read-only. Setting or adding entities on the inverse side alone produces no SQL INSERT or UPDATE for the foreign key.

This is the key to understanding mappedBy. Set both sides and Hibernate generates efficient SQL. Set only the inverse side and the relationship is silently not persisted.

One-to-many / many-to-one

This is the most common case. The "many" side always owns the relationship, because that is where the foreign key naturally lives.

java
1@Entity
2public class Department {
3    @Id
4    @GeneratedValue(strategy = GenerationType.IDENTITY)
5    private Long id;
6
7    private String name;
8
9    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
10    private List<Employee> employees = new ArrayList<>();
11
12    // Helper method to maintain both sides
13    public void addEmployee(Employee employee) {
14        employees.add(employee);
15        employee.setDepartment(this);
16    }
17
18    public void removeEmployee(Employee employee) {
19        employees.remove(employee);
20        employee.setDepartment(null);
21    }
22}
23
24@Entity
25public class Employee {
26    @Id
27    @GeneratedValue(strategy = GenerationType.IDENTITY)
28    private Long id;
29
30    private String name;
31
32    @ManyToOne(fetch = FetchType.LAZY)
33    @JoinColumn(name = "department_id")
34    private Department department;
35}

mappedBy = "department" refers to the department field in Employee. From it, Hibernate knows that Employee.department_id is the foreign key column and that Department.employees is a mirror that produces no SQL of its own.

The SQL Hibernate generates

sql
1CREATE TABLE department (
2    id BIGINT AUTO_INCREMENT PRIMARY KEY,
3    name VARCHAR(255)
4);
5
6CREATE TABLE employee (
7    id BIGINT AUTO_INCREMENT PRIMARY KEY,
8    name VARCHAR(255),
9    department_id BIGINT,
10    FOREIGN KEY (department_id) REFERENCES department(id)
11);

There is no join table. The foreign key sits on the employee table, where you want it.

What happens without mappedBy

Remove mappedBy from @OneToMany:

java
// BAD: missing mappedBy
@OneToMany(cascade = CascadeType.ALL)
private List<Employee> employees = new ArrayList<>();

Hibernate now treats Department.employees as a unidirectional @OneToMany and creates a join table:

sql
1CREATE TABLE department_employees (
2    department_id BIGINT,
3    employees_id BIGINT,
4    FOREIGN KEY (department_id) REFERENCES department(id),
5    FOREIGN KEY (employees_id) REFERENCES employee(id)
6);

This is valid JPA, but it is almost never the intended design for a one-to-many relationship. It adds storage, complicates queries and hurts performance.

One-to-one

Either side can own a one-to-one relationship. The side with @JoinColumn is the owner.

java
1@Entity
2public class User {
3    @Id
4    @GeneratedValue(strategy = GenerationType.IDENTITY)
5    private Long id;
6
7    private String username;
8
9    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
10    private UserProfile profile;
11}
12
13@Entity
14public class UserProfile {
15    @Id
16    @GeneratedValue(strategy = GenerationType.IDENTITY)
17    private Long id;
18
19    private String bio;
20
21    @OneToOne(fetch = FetchType.LAZY)
22    @JoinColumn(name = "user_id", unique = true)
23    private User user;
24}

The foreign key user_id lives in the user_profile table, and User.profile is the inverse side.

Lazy loading on the inverse @OneToOne side

On the inverse side (User.profile), Hibernate cannot tell whether the associated entity is null without querying the database. So FetchType.LAZY there is often not honored, and Hibernate issues an eager query to check whether a profile exists. The owning side (UserProfile.user) lazy-loads correctly, because Hibernate can read the user_id column.

If lazy loading on the inverse side matters for performance, share the primary key with @MapsId:

java
1@Entity
2public class UserProfile {
3    @Id
4    private Long id;  // Same as User.id
5
6    @OneToOne(fetch = FetchType.LAZY)
7    @MapsId
8    @JoinColumn(name = "id")
9    private User user;
10}

Many-to-many

A many-to-many relationship always needs a join table. One side must declare mappedBy, or Hibernate creates two join tables.

java
1@Entity
2public class Student {
3    @Id
4    @GeneratedValue(strategy = GenerationType.IDENTITY)
5    private Long id;
6
7    @ManyToMany
8    @JoinTable(
9        name = "student_course",
10        joinColumns = @JoinColumn(name = "student_id"),
11        inverseJoinColumns = @JoinColumn(name = "course_id")
12    )
13    private Set<Course> courses = new HashSet<>();
14}
15
16@Entity
17public class Course {
18    @Id
19    @GeneratedValue(strategy = GenerationType.IDENTITY)
20    private Long id;
21
22    @ManyToMany(mappedBy = "courses")
23    private Set<Student> students = new HashSet<>();
24}

Student owns the relationship. Adding or removing entries in student.getCourses() triggers inserts and deletes in student_course. Changing only course.getStudents() does nothing in the database.

The mappedBy string must match the field name

The mappedBy value must exactly match the Java field name on the owning side. It is case-sensitive and refers to the Java property, not the database column.

java
1// Owning side
2@ManyToOne
3@JoinColumn(name = "dept_id")  // database column name
4private Department department;  // Java field name
5
6// Inverse side
7@OneToMany(mappedBy = "department")  // must match Java field name, NOT "dept_id"
8private List<Employee> employees;

If the string is wrong, Hibernate fails at startup:

 
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property:
Employee.dept in Department.employees

This is easy to introduce when you rename a field during refactoring and forget the mappedBy string. IDEs like IntelliJ flag it, but not every refactoring tool does.

Keeping both sides in sync

Hibernate persists changes only from the owning side, so within the same persistence context (same transaction or session) you must set both sides, or the in-memory object graph becomes inconsistent.

java
1// WRONG: only setting the inverse side
2department.getEmployees().add(employee);
3// employee.department is still null -> no FK update in database
4
5// CORRECT: set the owning side (and optionally the inverse for in-memory consistency)
6employee.setDepartment(department);
7department.getEmployees().add(employee);

The recommended pattern is a helper method on the parent that maintains both sides, like Department.addEmployee() above. Setting only the inverse side is the most frequent mistake: the entity appears in memory, but the foreign key is never written.

Quick reference

RelationshipOwning side (has @JoinColumn)Inverse side (has mappedBy)Join table created
@OneToMany / @ManyToOne@ManyToOne side@OneToMany sideNo (FK on "many" table)
@OneToOneSide with @JoinColumnOther sideNo (FK on owner's table)
@ManyToManySide with @JoinTableOther sideYes (one join table)
@OneToMany without mappedByBoth sides treated as ownersN/AYes (unintended join table)

Other traps in bidirectional mappings

N+1 queries with eager fetching. FetchType.EAGER (the default for @ManyToOne and @OneToOne) loads associated entities immediately with each query, and for collections this produces N+1 queries. Use FetchType.LAZY and fetch explicitly with JOIN FETCH or @EntityGraph when you need the data.

Circular toString() and equals(). Bidirectional relationships create circular references. If both entities include each other in toString(), equals() or hashCode(), you get a StackOverflowError. Exclude the inverse side from these methods, or use only the entity's own fields (typically the primary key).


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design