views:

52

answers:

1

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 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)?

+1  A: 

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.

Affe
Thanks for the hints.I will use the "vendor specific magic strings" with string imported from a constant holder class (like HibernateHintConstants), which will ensure that a compile error is generated if I remove Hibernate (provided that I remember to remove the class with the constants related to Hibernate-specific hints).
leden