Hi guys
I have made a basic example in order to try to understand how the L2 cache in Hibernate is working. I am using JPA2 with the latest Hibernate Entitymanager, and EhCache as cache provider.
My example first finds and object by its primary key in the entity manager, and then does the same thing using a named query:
Code:
ElectionType electionType = em.find(ElectionType.class, 1L);
Query query = em.createNamedQuery("ElectionType.findByPk").setParameter("pk", 1L);
electionType = (ElectionType)query.getSingleResult();
The named query is defined like this:
Code:
@NamedQueries({
@NamedQuery(name = "ElectionType.findByPk", query = "SELECT et FROM ElectionType et WHERE et.pk = :pk")
})
On the first execution of em.find() I get a cache miss debug statement, and Hibernate executes a select query on the object.
On the first execution of the named query, I get no cache debug statements, and Hibernate executes the same select query.
On the second execution of em.find() I get a cache hit and no sql, but on the second execution of the named query, the same select query executes again.
I am wondering, shouldn't Hibernate be able to execute the named query on its cache only?
If not then I guess this is where the query cache comes in. Does it then mean that all named queries will be executed against the database if the query cache is disabled?
I have also tried enabling the query cache in my persistence.xml:
Code:
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="evotePU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myPU</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.use_minimal_puts" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="META-INF/ehcache.xml" />
<property name="hibernate.generate_statistics" value="true"/>
</properties>
</persistence-unit>
</persistence>
But it doesn't seem to have any effect. Is there anything else I have to do to mark this query as cacheable? Haven't found any parameters in @NamedQuery.
All this is probably obvious for experienced Hibernate users, but a newbie would really appreciate help in clarifying things here :)
Regards,
Anders