Hibernate Query Cache and Aggregate Queries

From what I understand, the query cache only caches the id’s of the result objects. So, for a query like a sum of a column, is there a way where the result of the query can still be cached, possibly also using the 2nd level cache. For example, if we defined some sort of result object that even gave it an id, but we don’t store it back in the database, can it just be cached by hibernate, or would I have to use some separate cache?

From what I understand, the query cache only caches the id’s of the result objects. So, for a query like a sum of a column, is there a way where the result of the query can still be cached, possibly also using the 2nd level cache.

The query cache works for projections as well. Check out this test on my high-performance-java-persistence GitHub repository.

For example, if we defined some sort of result object that even gave it an id, but we don’t store it back in the database, can it just be cached by hibernate, or would I have to use some separate cache?

Yes, you can give the DTO projection any id you want. Hibernate will store the corresponding dehydrated Object array anyway.

For more details, check out this article.