Mappingeasy0-2 years

Code adds a new `Book` to `author.getBooks()` and persists both. Every assertion in the method passes — `author.getBooks()` contains the book — but in the database `book.author_id` is `NULL`. No error was thrown. What went wrong?

Only one side of a bidirectional relationship writes the foreign key: the owning side. @OneToMany(mappedBy = "author") on Author.books says 'Book owns this relationship; this collection is only a view of it'. The code updated the view and never set book.author, so when Hibernate wrote the book it read book.author, found null, and wrote null. In memory the object graph is perfect, which is why the assertions pass; in the database there is no relationship at all. The fix is a helper on the entity that always sets both sides at once.

The lesson behind it →
More on Mapping