To use the query cache, you must first activate it using thehibernate.cache.use_query_cache="true" property in the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to hold the query and identifier sets.
Next, to use the query cache, you use the setCacheable(Boolean) method of the Query class. For example:
Session session =SessionFactory.openSession();
Query query =session.createQuery("FROM EMPLOYEE"); query.setCacheable(true); List users =query.list(); SessionFactory.closeSession(); Hibernate also supports very fine-grained cache support through the concept of a cache region. A cache region is part of the cache that's given a name.
Session session =SessionFactory.openSession();
Query query =session.createQuery("FROM EMPLOYEE"); query.setCacheable(true); query.setCacheRegion("employee"); List users =query.list(); SessionFactory.closeSession(); This code uses the method to tell Hibernate to store and look for the query in the employee area of the cache. |