A read-only property backed by SQL, evaluated whenever the entity is loaded.
@Entity
class Order {
@Id Long id;
@Formula("(select count(*) from order_items i where i.order_id = id)")
int itemCount;
}
select o.id, (select count(*) from order_items i where i.order_id = o.id) as itemCount
from orders o
It runs as a subquery on every load - fine for one row, costly for a list.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11