What is the best query strategy and entities configuration when using a second level cache

偶尔善良 提交于 2020-01-25 08:33:05

问题


What is the best query strategy and the best configuration for my entities when the second level cache is activated.

For example I have two entities User and Group with these relations :

One User to Many Group : the groups owned by the user. Here a collection of Group in the User class and a User attribute (the owner) in the Group class.

Many User to Many Group with attributes (status, date etc.) : the members of the groups. Because of the additionnals attibutes there is a specific class to map the intermediate table called UserGroup. There is a oneToMany collection of UserGroup in the User class and another one in the Group class.

The related attributes or collections are configured to be retrieved in Lazy mode. All the entities class and collections are cacheable.

So far if I wanted the user's groups to be retrieved with their member I was making a request of this type :

select g from Group g left join fetch UserGroup ug left join fetch ug.user u where g.group.owner = :idOwner

Now with the second level cache that works as a key-value store, isn't it easier and effective to get the user from his id and then let hibernate recover the groups and the members in Lazy mode to finally save the data in the second level cache ? The next query will use the cache, so what is the benefit of using a join ? Also I wouldn't have to configure any optimized queries to be cached.

Thanks.


回答1:


I can't really comment on the cost of joins (Hibernate/JPA experts out there will probably have better answers in that regard), but I can comment on caching itself.

What matters to caching is really how often these entities and collections are updated. If you have a query that spans multiple entities and collections, the moment one of those entities, or the collections are modified, even in the smallest possible way, the query is invalidated. So, I'd strongly recommend caching entities and collections that are read mostly. These invalidations are tracked per type btw, so even adding a new entity (which is not part of the query resultset) would invalidate the query.

Even if not using queries, if just retrieving an entity and a collection reference, the moment an entity in the collection is modified, or the collection is modified somehow (entity added/remove), then the collection gets invalidated.

I'd favour selectively enabling caching rather than just taking all entities and collections and making them cacheable right away. Besides invalidations, you also need to consider that caches take up memory and resources.



来源:https://stackoverflow.com/questions/58506314/what-is-the-best-query-strategy-and-entities-configuration-when-using-a-second-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!