Now, if we call this method one more time, Hibernate executes the same SQL query:

SELECT
p.id AS col_0_0_,
p.title AS col_1_0_,
p.created_on AS col_2_0_,
count(pc.id) AS col_3_0_
FROM
post_comment pc
LEFT OUTER JOIN
post p
ON pc.post_id=p.id
GROUP BY
p.id,
p.title
ORDER BY
p.created_on DESC
LIMIT
5

But, we don’t want that since the front page is accessed very often, and we have more reads than writes into our system.

Caching the result set

So, if we pass the cacheable parameter set to true, Hibernate can cache the query, and we can see that in the query cache region :

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

While using the Hibernate Query Cache for entities is not uncommon, the second-level Query Cache works also for DTO projections, and it can be suitable if we have SQL queries that are executed often, but the underlying tables don’t change frequently.

Subscribe to our Newsletter

* indicates required

Email Address *

10 000readers have found this blog worth following!

If you subscribeto my newsletter, you'll get:

A free sampleof my Video Course about running Integration tests at warp-speed using Docker and tmpfs