Video in progress

Strong Junior 🐻 Hibernate and JPA

In a bidirectional association, if you add an element only to the collection on the `mappedBy` side, what gets written to the database?

Nothing. The owning side controls the FK, which is the side with @ManyToOne. Hibernate ignores changes in the mappedBy collection for the FK, so you must also call child.setParent(parent).

📖 Answer

@Entity
class Author {
    @OneToMany(mappedBy = "author")
    private List<Book> books = new ArrayList<>();
}

@Entity
class Book {
    @ManyToOne(fetch = FetchType.LAZY)
    private Author author; // owning side: the author_id column is here
}

This code does not fill in author_id:

author.getBooks().add(book);   // in memory only

Until you call book.setAuthor(author), book.author_id stays null. mappedBy tells Hibernate "this association is actually written on the other side, don't look at me".

The reverse is confusing too: if you only call book.setAuthor(author), it's written to the database correctly, but within the same transaction author.getBooks() won't show the new book, if the collection has already been loaded.

That's why you write a helper method that updates both sides together:

public void addBook(Book b) {
    books.add(b);
    b.setAuthor(this);
}