This will introduce the use of query caching, first-level caching, level two caching in Hibernate, and the integration of spring using query caching in Hibernatetemplate. , here is Hibernate3, using hibernate4 similar, but not hibernatetemplate,
Direct
Query query = getsession (). CreateQuery (HQL);
Turn on level two caching
Query.setcacheable (TRUE);
Ehcache is one of Hibernate's level two cache technology, can store the query data in memory or disk, save the next same query to query the database again, greatly reduce the database pressure;
Attention points for the use of Ehcache
When the table data is modified in hibernate (Save,update,delete and so on), then Ehcache will automatically delete all caches in the cache about this table (so that synchronization can be achieved). However, for tables that are frequently modified by the data, it is possible to lose the meaning of the cache (which does not relieve the pressure on the database); in the case of less update of table data, Ehcache generally uses tables that perform write operations less often (including update,insert,delete, etc.) [ Hibernate's Level Two cache is also the same); In the case of the concurrency requirement is not very strict, the cache in the two machines can not be synchronized in real time;
First, add the configuration to the Hibernate.cfg.xml configuration file, adding the following to the mapping tag in Hibernate.cfg.xml:
<!--Hibernate 3.3 and higher - <!--<property name= "Hibernate.cache.region.factory_class" >net.sf.ehcache.hibernate.ehcacheregionfactory </property><property name= "Hibernate.cache.region.factory_class" > Net.sf.ehcache.hibernate.singletonehcacheregionfactory</property> - <!--hibernate3.0-3.2 Cache config - <!--<property name= "Hibernate.cache.region.factory_class" >net.sf.ehcache.hibernate.ehcacheprovider</ Property> - < Propertyname= "Hibernate.cache.provider_class">Net.sf.ehcache.hibernate.SingletonEhCacheProvider</ Property> <!--Enable second-level Cache and Query cache Settings - < Propertyname= "Hibernate.cache.use_second_level_cache">True</ Property> < Propertyname= "Hibernate.cache.use_query_cache">True</ Property>
If you are integrating in the spring configuration file, then you have to configure the configuration of the relevant sessionfactory in your Applicationcontext.xml
<propKey= "Hibernate.cache.use_query_cache">True</prop><propKey= "Hibernate.cache.use_second_level_cache">True</prop><propKey= "Hibernate.cache.provider_class">Org.hibernate.cache.EhCacheProvider</prop>
Then add the properties that use the cache in the Hibernate.cfg.xml configuration file
<!--- <class = " Com.hoo.hibernate.entity.User " usage=" Read-write"/>
Of course you can also add the following format information to the User.hbm.xml mapping file that requires the cache's configuration class node:
<name= "Com.hoo.hibernate.entity.User" table= "User" lazy = "false"><usage= "transactional|read-write| Nonstrict-read-write|read-only "/>
Note: The cache node element should follow the class element
About choosing a cache policy by:
Ehcache does not support transactional, the other three kinds can be supported.
read-only: Without modification, it can be read-only cache, note: Under this policy, if you modify the database directly, even if you can see the foreground display effect, but to modify the object to the cache will be reported Error,cache does not take effect. Another: Deleting a record will cause an error because the object in read-only mode cannot be deleted from the cache.
Read-write: the need to update the data, then use a read/write cache is appropriate, provided that the database is not serializable transaction isolation level (serialization of transaction isolation levels)
SELECT @ @tx_isolation View
nonstrict-read-write: Only occasionally need to update the data (that is, two transactions are not common to update the same record at the same time), and do not require very strict transaction isolation, it is more appropriate to use a non-strict read/write cache policy.
If you use the annotation method, there is no User.hbm.xml, then you can also use annotations to configure the cache
@Cache (usage = cacheconcurrencystrategy.read_write) publicclassimplements Serializable {}
Using the cache at the DAO layer, the code is as follows
Session s =hibernatesessionfactory.getsession (); Criteria C= S.createcriteria (User.class); C.setcacheable (true);//This sentence must haveSystem.out.println ("First time read"); List<User> users =c.list (); System.out.println (Users.size ()); Hibernatesessionfactory.closesession (); S=hibernatesessionfactory.getsession (); C= S.createcriteria (User.class); C.setcacheable (true);//This sentence must haveSystem.out.println ("Second Read"); Users=c.list (); System.out.println (Users.size ()); Hibernatesessionfactory.closesession ();
You will find that the second query does not print the SQL statements, but instead directly uses the objects in the cache.
If your hibernate and spring are integrated, you can use Hibernatetemplate to set the cache
Gethibernatetemplate (). Setcachequeries (true); return gethibernatetemplate (). Find ("from User");
When you integrate spring, if your hibernatetemplate template is configured in the Spring IOC container, you can enable the query cache
<BeanID= "Hibernatetemplate"class= "Org.springframework.orm.hibernate3.HibernateTemplate"> < Propertyname= "Sessionfactory"> <refBean= "Sessionfactory" /> </ Property> < Propertyname= "Cachequeries"> <value>True</value> </ Property></Bean>
After that, you inject hibernatetemplate into the DAO module where you inject sessionfactory.
These are the spring and hibernate configuration, the following mainly combined with the above used Ehcache, to complete the ehcache.xml configuration. If you do not configure Ehcache, the configuration of Defaultcache is used by default.
<Cachename= "Com.hoo.hibernate.entity.User"maxelementsinmemory= "10000"Eternal= "false"Timetoidleseconds= "+"Timetoliveseconds= "All"Overflowtodisk= "true" /><!--hbm Files Find the policy for the cache method name: If you do not specify a property value for name in the region= "Ehcache.xml" in the hbm file, Use the cache with the name Com.hoo.hibernate.entity.User, or Defaultcache if there is no cache name that matches the class name. If user contains a set set, you need to specify its cache for example user contains Cityset collection, you need to add the following configuration to Ehcache.xml -<Cachename= "Com.hoo.hibernate.entity.citySet"maxelementsinmemory= "10000"Eternal= "false"Timetoidleseconds= "+"Timetoliveseconds= "All"Overflowtodisk= "true" />
If you are using Hibernate's query cache, you need to include the following configuration in Ehcache.xml
<Cachename= "Org.hibernate.cache.UpdateTimestampsCache"maxelementsinmemory= "the"Eternal= "true"Overflowtodisk= "true" /><Cachename= "Org.hibernate.cache.StandardQueryCache"maxelementsinmemory= "10000"Eternal= "false"Timetoliveseconds= "+"Overflowtodisk= "true" />
Debugging time Use log4j Log4j.logger.org.hibernate.cache=debug, more convenient to see Ehcache operation process, mainly for debugging process, the actual application release, please comment out, so as not to affect performance
With Ehcache, it is normal to print SQL statements because query cache is set to True to create two cache zones: one for saving query result sets (Org.hibernate.cache.StandardQueryCache); The other is the timestamp (Org.hibernate.cache.UpdateTimestampsCache) of the series of tables that were used to hold the most recent query. Note: In the query cache, it does not cache the exact state of the entities contained in the result set, it caches only the values of the identifier properties of those entities, and the results of each value type. The print SQL statement needs to be compared to the most recent cache content and changed to the cache, so the query cache is typically used in conjunction with the level two cache.
Using Ehcache cache in Spring, Hibernate (2)