Video in progress
How do you make Hibernate lighter on read-only queries?
I mark the transaction readOnly, so Hibernate keeps no snapshots and does not flush. Where possible I return a DTO projection instead of an entity, because it never enters the persistence context at all.
📖 Answer
For every entity returned by a plain find or a query, Hibernate keeps a copy of its state (the loaded state), and dirty checking compares against it at commit. For reads this is wasted memory and CPU.
With @Transactional(readOnly = true) in Spring, Spring switches the Session to FlushMode.MANUAL and turns on Hibernate's default read-only mode. Hibernate does not keep snapshots for newly loaded entities, and no flush happens. With some drivers Connection.setReadOnly(true) is sent as well, which helps with replica routing.
There is also a hint for a single query:
List<Order> list = em.createQuery("select o from Order o where o.status = :s", Order.class)
.setParameter("s", Status.NEW)
.setHint(HibernateHints.HINT_READ_ONLY, true)
.getResultList();
But the biggest win is skipping the entity altogether. If the screen needs 5 columns, there is no point loading a 30-column entity and its lazy proxies:
record OrderRow(Long id, String number, BigDecimal total) {}
em.createQuery("select new com.shop.OrderRow(o.id, o.number, o.total) from Order o", OrderRow.class)
In Hibernate 6 you can map to a record even without new inside the select, but writing it with new is clearer.
One warning: if you modify a read-only entity, Hibernate silently ignores it. No error is thrown, so don't call a writing method from a readOnly method by accident.
Sign up to mark studied questions and save your progress.