Video in progress

Strong Middle 🐻 Hibernate and JPA

How does `@ManyToOne(optional = false)` differ from `@JoinColumn(nullable = false)`, and how does it affect the SQL?

nullable = false is mostly for DDL: it puts NOT NULL on the column. optional = false tells Hibernate the association is always present: it can use an inner join instead of a left outer join in joins, and it can check for a null value before flush. Writing both together is normal.

📖 Answer

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;

The effect of optional shows up mostly in EAGER loading and in entity graphs. With optional = true (the default), Hibernate does a left outer join, since customer might be missing. With false, it can write an inner join, which is often better for the optimizer, especially with several joins.

Where to be careful: if the data in the database doesn't match the mapping, an inner join silently loses rows. If an old table has orders with a null customer_id and you set optional = false, those orders "disappear" from lists. That's why I first add NOT NULL in a migration and only then change the mapping.

On the validation side: if hibernate.check_nullability is enabled, Hibernate stops an optional = false association with a null value at flush with a PropertyValueException. This setting is off by default if Bean Validation is on the classpath, because it assumes @NotNull is used there.

My conclusion is short: on a mandatory association I put all three: optional = false, nullable = false and NOT NULL in the migration. Each one works in its own layer.