开发者

HIbernate Entity Manager: How to cache queries?

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:

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开发者_Go百科 by the SessionFactory's createQuery() method), does not have the org.hibernate.Query.setCacheable() method.

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


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

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 EntityManager to a Session before ever creating the query.

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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜