Sub topic 6
Modeling associations and the owning side
What this chapter assumes
You should know how to map a basic @Entity with an @Id, and you should know what a foreign key and a join table are in SQL. The examples reuse the Author and Book entities from the earlier chapters.
An association is a reference from one entity to another, such as a book pointing to its author. Mapping one correctly means answering two questions. Which side writes the foreign key, and what should happen to the other side when this one is saved or deleted?
The owning side and the inverse side
A relational database stores a relationship in one place, as a foreign key column on one table or as rows in a join table. Java objects store it twice. Book holds an Author, and Author holds a List<Book>. These two references can disagree, so JPA needs a rule for which one counts.
- The owning side is the reference JPA reads when it writes the relationship to the database. It maps to the foreign key column or the join table.
- The inverse side is the other reference. It is marked with
mappedBy, and JPA ignores it when writing.
For a bidirectional one-to-many, the owning side is always the many side, because the foreign key lives in its table.
One-to-many and many-to-one
Here are the two sides from the earlier code, reduced to the association itself.
// In Author (inverse side)
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books = new ArrayList<>();
// In Book (owning side)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "author_id")
private Author author;@JoinColumn names the foreign key column. optional = false makes the column NOT NULL in generated schemas and tells Hibernate that a null author is invalid. The value of mappedBy is the field name in the other entity, here author. It is not a column name.
Keep both sides in sync with a helper
JPA writes only the owning side. If you do this, the database gets no foreign key:
Author author = new Author("Ursula K. Le Guin");
author.getBooks().add(new Book("A Wizard of Earthsea", 1968)); // inverse side only
authors.save(author); // fails: author_id is NOT NULL and Book.author is nullSetting only the inverse side also leaves the in-memory graph inconsistent. book.getAuthor() returns null until the entity is reloaded. The addBook helper fixes both problems by updating both sides in one call:
public void addBook(Book book) {
books.add(book);
book.setAuthor(this);
}Make the setter on Book package-private, as in the earlier code, so callers go through the helper. Add a matching removeBook that removes the book from the list and sets its author to null. That only makes sense when the column is nullable or when orphanRemoval will delete the book.
Many-to-many with a join table
A many-to-many relationship has no foreign key on either entity table. The database needs a third table, the join table, with one row per pair. Here a book has many tags and a tag has many books.
You choose the owning side. It declares the @JoinTable, and the other side uses mappedBy. Add this to Book:
// In Book (owning side), plus imports for Set and HashSet
@ManyToMany
@JoinTable(
name = "book_tags",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private Set<Tag> tags = new HashSet<>();
public void addTag(Tag tag) {
tags.add(tag);
tag.getBooks().add(this);
}
public void removeTag(Tag tag) {
tags.remove(tag);
tag.getBooks().remove(this);
}The inverse side is a new entity:
import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "tags")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name;
@ManyToMany(mappedBy = "tags")
private Set<Book> books = new HashSet<>();
protected Tag() {
}
public Tag(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
public Set<Book> getBooks() { return books; }
}Use a Set rather than a List for many-to-many collections. When you remove one element from a List mapped as a bag, Hibernate may delete every join row for the owner and insert the remaining rows again. A Set produces a single delete for the removed pair.
The Set relies on equals and hashCode, which a later chapter covers. Until then, remember that HashSet behaves badly if those methods are wrong.
If the link needs its own data, such as the date a tag was added, @ManyToMany cannot hold it. Model the join table as an entity with two @ManyToOne associations instead.
Cascade and orphan removal
By default, saving an author does not save the books in its list. cascade copies persistence operations from a parent to its children.
| Setting | Effect |
|---|---|
| `CascadeType.PERSIST` | Saving the parent also saves new children |
| `CascadeType.MERGE` | Merging the parent also merges children |
| `CascadeType.REMOVE` | Deleting the parent deletes the children |
| `CascadeType.ALL` | All of the above, plus refresh and detach |
| `orphanRemoval = true` | A child removed from the parent's collection is deleted |
Use cascade only where the parent owns the child's lifecycle. A book cannot exist without its author, so ALL and orphanRemoval fit Author.books. They do not fit Book.tags. Deleting a book must not delete a tag that other books still use, and REMOVE on a many-to-many would do exactly that.
Fetch defaults
The defaults depend on the association type. They matter because they decide how many queries run.
| Annotation | Default fetch | Recommended |
|---|---|---|
| `@ManyToOne` | `EAGER` | Set `LAZY` explicitly |
| `@OneToOne` | `EAGER` | Set `LAZY` where possible |
| `@OneToMany` | `LAZY` | Keep `LAZY` |
| `@ManyToMany` | `LAZY` | Keep `LAZY` |
Eager @ManyToOne is the default people forget, and it is a common source of unexpected extra selects. The chapter on fetching explains how to load what you need with join fetch and entity graphs.
Common errors
- Missing
mappedBy. Without it, Hibernate treats both sides as owners. It creates an extra join table, such asauthors_books, and the foreign key onbooksis never filled. - Wrong
mappedByvalue. The value must match the field name on the owning entity exactly. A typo fails at startup with a "mappedBy reference an unknown target entity property" error. - Updating only the inverse side. The change is silently ignored on save. Always go through a helper method.
- Infinite recursion. A
toString()or JSON serializer that walksauthor.booksand thenbook.authorloops forever. Leave the association out oftoStringand return DTOs from your web layer. - Exposing the mutable collection.
getBooks()returns the live list, so callers can bypass the helper. ReturnCollections.unmodifiableList(books)if you want to prevent that. Keep the field itself mutable.
Exercise
A Course entity declares @ManyToMany(mappedBy = "courses") Set<Student> students. Student declares @ManyToMany @JoinTable(name = "enrollments", ...) Set<Course> courses. You run course.getStudents().add(student) inside a transaction and commit. No row appears in enrollments. Why, and what is the fix?
Show answer
Student.courses is the owning side because it has the @JoinTable, and Course.students is the inverse side because it uses mappedBy. Hibernate writes join rows only from the owning side. Adding to the inverse collection alone changes nothing in the database. The fix is to add the course to student.getCourses() as well, ideally through a helper such as student.addCourse(course) that updates both collections.