Video in progress
How do you map a database view or the result of a complex SQL query as a Hibernate entity?
I map a view as an ordinary @Entity + @Table(name = "view_name") and add @Immutable, so Hibernate doesn't try to write to it. If you can't create a view, Hibernate's @Subselect annotation makes the SQL itself the source of the entity; with @Synchronize you tell it which tables it depends on.
📖 Answer
With a view:
create view order_summary as
select o.id, o.number, c.name as customer_name, sum(i.price * i.qty) as total
from orders o join customer c on c.id = o.customer_id
join order_item i on i.order_id = o.id
group by o.id, o.number, c.name;
@Entity
@Immutable
@Table(name = "order_summary")
class OrderSummary {
@Id Long id;
String number;
String customerName;
BigDecimal total;
}
Now plain JPQL on OrderSummary, a Spring Data repository, pagination: everything works. @Immutable matters: without it, Hibernate might do dirty checking and try to send an UPDATE to the view.
With @Subselect, without a view:
@Entity
@Immutable
@Subselect("""
select o.id, o.number, sum(i.price * i.qty) as total
from orders o join order_item i on i.order_id = o.id
group by o.id, o.number""")
@Synchronize({"orders", "order_item"})
class OrderTotal { @Id Long id; String number; BigDecimal total; }
Hibernate puts this SQL inside from (...) on every query. @Synchronize says that before OrderTotal is queried, unflushed changes in those tables must be flushed; otherwise you'd see a stale total within a single transaction.
What I watch for: the @Id must be unique, otherwise the persistence context merges rows with the same id into a single object. A view with heavy aggregation may need a materialized view and a plan for refreshing it. And the SQL is native, meaning it depends on the dialect.
Sign up to mark studied questions and save your progress.