Video in progress
When does it pay off to do CQRS-style writes with Hibernate entities and handle the read side differently?
When read needs differ sharply from the write model: lists, filters and reports that join many tables. Writes go through entities and invariants, while reads go through DTO projections, SQL views or a separate read database.
📖 Answer
When a single model tries to do both jobs, you get a typical picture: @OneToMany associations get added to entities just for screens, EntityGraphs multiply, and the whole graph is loaded just to map it to a DTO. The write flow also carries that heavy graph around.
I see CQRS at two levels.
The light level: one database, one service. Writes: repository + entity + @Transactional. Reads: a separate QueryService that never returns entities.
@Repository
class OrderQueries {
private final JdbcClient jdbc;
List<OrderListRow> forCustomer(long customerId) {
return jdbc.sql("""
select o.id, o.number, o.total, c.name as customer_name,
count(l.id) as lines
from orders o
join customer c on c.id = o.customer_id
left join order_line l on l.order_id = o.id
where o.customer_id = :cid
group by o.id, c.name""")
.param("cid", customerId)
.query(OrderListRow.class).list();
}
}
There is no persistence context, dirty checking or lazy loading here at all. For most projects this is enough.
The heavy level: a separate read store (Elasticsearch, a denormalized table) updated through events. This requires eventual consistency, event processing and a rebuild mechanism. I only choose it when there is a real reason: full-text search, a very high read load, or an API for other teams.
The decision point: if you are being forced to add mappings to an entity just for reads, it is time for light CQRS.
Sign up to mark studied questions and save your progress.