java HIbernate 实体管理器:如何缓存查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:27:08  来源:igfitidea点击:

HIbernate Entity Manager: How to cache queries?

javahibernatecachingjpa-2.0

提问by eold

I am using the Hibernate 3.5.1 and EntityManager for data persistence (with JPA 2.0 and EHCache 1.5). I can obtain the query by the following code:

我使用 Hibernate 3.5.1 和 EntityManager 进行数据持久化(使用 JPA 2.0 和 EHCache 1.5)。我可以通过以下代码获取查询:

EntityManager em;
...
Query query = em.createQuery(...);
...

Now, the problem is that EntityManager's createQuery() method returns javax.persistence.Query which, unlike org.hibernate.Query (returned by the SessionFactory's createQuery() method), does not have the org.hibernate.Query.setCacheable() method.

现在,问题是 EntityManager 的 createQuery() 方法返回 javax.persistence.Query,与 org.hibernate.Query(由 SessionFactory 的 createQuery() 方法返回)不同,它没有 org.hibernate.Query.setCacheable() 方法.

How am I, then, supposed to cache the queries with EntityManager (or some other part of Hibernate)?

那么,我应该如何使用 EntityManager(或 Hibernate 的其他部分)缓存查询?

回答by Affe

You can use the unwrap method to get at the vendor implementation when you want to use vendor specific extensions. e.g.,

当您想使用供应商特定的扩展时,您可以使用 unwrap 方法来获取供应商实现。例如,

org.hibernate.Query hquery = query.unwrap(org.hibernate.Query.class);

Then you can work with the vendor specific interface. Alternately you could just unwrap your EntityManagerto a Sessionbefore ever creating the query.

然后您可以使用供应商特定的接口。或者,您可以在创建查询之前EntityManager将其解包到 a Session

If you don't want to have any hibernate imports in your code, you could also do

如果您不想在代码中包含任何休眠导入,您也可以这样做

query.setHint("org.hibernate.cacheable", Boolean.TRUE);

Really up to you which way you'd rather introduce vendor dependence.

真的由您决定,您宁愿采用哪种方式引入供应商依赖性。

I would favor the first as it will fail with an exception if hibernate is removed from your dependencies sending up a big red "Hey you developer changing this, there was a vendor dependence here." Whereas the hint simply does nothing if it's not understood by the provider.

我倾向于第一个,因为如果从您的依赖项中删除 hibernate,它将失败并出现异常,发送一个大红色“嘿,您的开发人员正在更改此设置,这里存在供应商依赖性。” 而如果提供者不理解提示,则它什么也不做。

Other persons would rather tolerate having vendor dependent magic strings in code over needing to have a compile time vendor dependence.

其他人宁愿容忍在代码中具有依赖于供应商的魔法字符串而不是需要具有编译时供应商依赖性。