Because the query cache relies on level two caching, you must first turn on level two caching.
The steps are as follows:
First, open the query cache with a configuration file
Situation one, project has hibernate.cfg.xml file
Open the query cache function by modifying the Hibernate.cfg.xml file
<!--turn on level two cache with Ehcache Cache--
<property name= "Hibernate.cache.use_second_level_cache" >true</ property>
<property name= "Hibernate.cache.provider_class" >org.hibernate.cache.ehcacheprovider</ Property>
<!--open Query Cache-
<property name= "Hibernate.cache.use_query_cache" >true</ Property>
Scenario two, the project integrates the spring framework without the Hibernate.cfg.xml file
Open the query cache function by modifying the Applicationcontext.xml file
<bean id= "sessionfactory"
class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
......
<property name= "Hibernateproperties" >
<props> ...
<!--turn on level two cache, use Ehcache Cache--
<prop key= "Hibernate.cache.use_second_level_cache" >true</prop>
<prop key= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>
< !--Open Query Cache--
<prop key= "Hibernate.cache.use_query_cache" >true</prop> ...
</props>
</property>
<property name= "mappingresources" >
<list>
< value>edu/po/users.hbm.xml</value>
<value>edu/po/TLog.hbm.xml</value>
</list >
</property>
</bean>
Next, use the query caching feature by Query.setcacheable (true) or hibernatetemplate.setcachequeries (true)
To use the query cache, you must have a cache object for the entity class in the level two cache, the configuration of level two cache is shown in the blog Hibernate two cache, using the Ehache cache framework
example, as follows
Session Session3 = Sessionfactory.opensession ();
Session3.begintransaction ();
Query query = Session3.createquery ("from Users where id =: id");
Query.setparameter ("id", 6);
Query.setcacheable (TRUE); Enable query caching
Users User3 = (users) query.list (). get (0);
System.out.println ("User name:" + user3.getusername ());
Session3.gettransaction (). commit ();
Session3.close ();
Hibernatetemplate hibernatetemplate = new Hibernatetemplate (sessionfactory);
Hibernatetemplate.setcachequeries (TRUE); Open Query Cache
Users User9 = (users) hibernatetemplate.find ("from Users where id =?", 6). Get (0);
System.out.println ("User name:" + user9.getusername ());
Item Demo:https://github.com/zengyh/sshwebproject.git