Video in progress

Strong Middle 🐻 Hibernate and JPA

How do `@Formula` and `@SQLRestriction` (formerly `@Where`) work in Hibernate, and what are their dangers?

@Formula computes a field from a SQL expression, and it is added to every select as a subquery. @SQLRestriction adds a SQL where condition every time the entity or collection is loaded; in Hibernate 6.3 @Where was deprecated and replaced by this name.

📖 Answer

@Entity
class Customer {
    @Id Long id;

    @Formula("(select count(*) from orders o where o.customer_id = id)")
    int orderCount;

    @OneToMany(mappedBy = "customer")
    @SQLRestriction("status <> 'CANCELLED'")
    List<Order> activeOrders;
}

@Formula is convenient, but every time a Customer is read, that subquery runs too: on a list page with 1000 customers, that's 1000 correlated counts. Making it lazy works only with bytecode enhancement. The SQL inside the formula is native, so column names and dialect differences are your responsibility. The field is read-only; you can't write to it.

The main trap with @SQLRestriction is that it's hidden. Someone thinks customer.getActiveOrders() is what they need, goes looking for the cancelled ones, and can't find them. If you put it on the entity class itself, find() is filtered too: the application treats a row that exists in the database as "missing", and a unique constraint error shows up unexpectedly.

If the condition has to be dynamic (tenant, date), @Filter is better, since you can turn it on and off at the session level.

I use both only for a clear and stable rule. For report data, a separate query or a view is a more open and manageable way.