2nd level cache not working with 1:m lazy loaded collection

  • Can somebody please tell me, why this happens, although all related entities are cached properly?

This is a limitation that is going to be fixed in Hibernate ORM 6.5 via https://github.com/hibernate/hibernate-orm/pull/7543

  • And why is everything working when collections are set to eager fetching by default (which is no option at all)?

When Hibernate ORM loads an entity/collection from cache, it will ensure that the configured FetchType of nested associations are respected. If you run a query that join fetches a lazy association or specify a fetch/load graph for such an association, then Hibernate ORM is currently not able to efficiently initialize these associations. Until version 6.5 you will have to initialize associations manually within your transaction with e.g. Hibernate.initialize( object ).

  • And as a last point: why does this not affect query caches? (Query caches work as expected without any further modification of the parent entity, I don’t even have to annotate the postComments collection.)

Query caches in Hibernate ORM 6 store the full data, whereas in 5 it stored only the keys of entities. I guess you are using ORM 6, so you won’t have any trouble there, but note that if you also want to cache entity data by id, using the full query cache layout might not be the best choice, especially if you expect that the entity cache hit rate is very high (i.e. if the cached entity is reference data).

You’ll be happy to hear though that this is also covered by this PR. It introduces a way to specify how an entity should be stored in a query cache. By default, ORM 6.5 will only store the primary key of an entity if the entity is marked as cacheable i.e. assuming a high cache hit rate. You can fine tune that though.

1 Like