Video in progress

Strong Middle 🌱 Spring

What problems does @ManyToOne being EAGER by default cause?

In the JPA spec @ManyToOne and @OneToOne are EAGER by default: when an entity is loaded, the related object is fetched by force too. In JPQL queries this gives an extra SELECT per row (N+1), and you can't turn it off at the query level afterward.

📖 Answer

@Entity
class OrderLine {
    @ManyToOne               // default: FetchType.EAGER
    private Product product;
    @ManyToOne
    private Order order;
}

If select l from OrderLine l where l.order.id = :id returns 100 rows, Hibernate does a separate SELECT for each unique Product and Order. findById often fetches with a JOIN, so the same entity is loaded differently in different queries, and the problem shows up only on a particular screen.

The main downside of EAGER is that you can't turn it off. With LAZY, you fetch where you need to with join fetch or @EntityGraph. With EAGER, no query can say "not this time".

That's why a widespread rule is:

@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Product product;

Make all *ToOne relationships LAZY and ask explicitly for the graph you need in each use case.

A couple more points:

  • The inverse side of a @OneToOne (mappedBy) is often loaded eagerly even if you write LAZY: Hibernate has to know whether the relationship exists in order to put in a proxy. In many cases the solution is a shared primary key with @MapsId, or making the relationship unidirectional.
  • If you only need the id, getId() on a LAZY proxy doesn't go to the database.
  • Hibernate statistics (hibernate.generate_statistics=true) or a library that checks the query count in a test will catch N+1 in CI.