0%
Relationships Between Entities

Relationships

Where the generated SQL stops being obvious, and where N+1 queries are born.

15-20 min

Relationships Between Entities

A standalone entity is an exercise. The real work begins when entities reference each other: an author has books, an order has lines, a book belongs to categories. This is where the ORM stops doing what you expect, because Java and SQL don't express the same thing.

In Java, an association is bidirectional by nature: if commande.getLignes() contains a line, it's natural that ligne.getCommande() returns that order. In SQL, there is only one thing: a foreign key column, in a single table, on a single side. Java's bidirectionality is a fiction that you maintain by hand. When you forget to maintain it, you end up with an entity whose two sides contradict each other — and Hibernate will write what the owning side says, not what your code says.

Three families of problems come out of this lesson, and each one shows up in production. The first is LazyInitializationException, which surfaces when you read a relationship after the transaction has closed. The second is the REMOVE cascade, which deletes more rows than expected because it traverses the entire graph. The third is the unidirectional @OneToMany, which creates a join table nobody asked for and makes every deletion quadratic.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!