如何仅在会话级别启用休眠查询缓存? [英] How to enable hibernate query cache on a session level only?

查看:123
本文介绍了如何仅在会话级别启用休眠查询缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个查询在单个线程中被多次调用,而我只想缓存该线程的查询(及其结果)(或者因为每个线程使用一个会话, ,我该怎么做?



注意:我的第二级缓存已打开,但主要用于session.get(...)。但我不想将它用于查询缓存,因为我只需要它在我的线程(/ session)期间存活。



谢谢

解决方案

这里的底线是:您可以手动缓存你的查询结果,或者你可以让Hibernate去做。尽管将查询缓存的生命周期限制为会话的时间一般没有意义,但可以使用以下方法完成: //docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch20.html#performance-querycacherel =nofollow noreferrer>启用查询缓存



2)为特定查询区域提供特定区域并将其标记为可缓存:

 查询query = ...; 
query.setCacheable(true).setCacheRegion(MY_SPECIAL_QUERY);

3)在会话结束时逐出缓存(如果您 REALLY 确定这就是你想要做的):

  SessionFactory sessionFactory = ...; 
sessionFactory.evictQueries(MY_SPECIAL_QUERY);


What if I have a query that gets called multiple times in a single thread, and I just want to cache that query (and its result) for that thread (or for that session since I'm using one session per thread), how can I do that ?

Note: My 2nd level cache is turned on but it's used mostly for session.get(...). But I do not want to use it for my query cache because I only need it to live for the duration of my thread ( / session ).

Thanks

解决方案

The bottom line here is: you can either manually cache your query results or you can ask Hibernate to do it. While it generally makes little sense to restrict your query cache lifetime to that of session, it can be done using the following approach:

1) Enable query cache

2) Dedicate a specific region for query in question and mark it as cacheable:

Query query = ...;
query.setCacheable(true).setCacheRegion("MY_SPECIAL_QUERY");

3) Evict your query from cache at the end of the session (if you're REALLY sure that's what you want to do):

SessionFactory sessionFactory = ...;
sessionFactory.evictQueries("MY_SPECIAL_QUERY");

这篇关于如何仅在会话级别启用休眠查询缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆