One: Knowledge points
1: Caching Concepts and classifications
Cache: Create a space in memory to store the data that should be stored in the database on the hard disk.
Hibernate has three kinds of caches:
First-level caching
Second-level cache
Query cache
2: Features of various caches
(1) session level cache is a primary cache, the session cannot share the cache
(2) Level two cache is also called sessionfactory level cache, can cross session
(3) Query cache: Duplicate query, query object is consistent with the condition, can be found from the level two cache. If the query is not duplicated, a level two cache is not used.
3: How to configure Level two cache
(1), first to open the level two cache, add the following configuration in Hibernate.cfg.xml:
<property name= "Hibernate.cache.use_second_level_cache" >true</property>
(2), Hibernate's level two cache is implemented using a third-party caching tool, so we need to specify which of hibernate to use
Caching tools. The following configuration specifies that Hibernate uses the Ehcache cache tool.
<property name= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>
(3): Join Ehcache.xml
<--
Maxelementsinmemory Maximum Cache Object
Eternal = False memory can be cleared
Timetoidleseconds if the object is not queried for how long, clear the object
TimetolivesecondsObject maximum lifetime, generally greater than timetoidleseconds
Overflowtodisk memory overflow, storage on the hard disk <diskstore path= "Java.io.tmpdir"/>
-
<defaultcache
Maxelementsinmemory= "10000"
Eternal= "false"
Timetoidleseconds= "120"
Timetoliveseconds= "120"
Overflowtodisk= "true"
/>
(4): Add annotation before objects that require a level two cache
@Cache (usage = cacheconcurrencystrategy.nonstrict_read_write)
@Entity
public class User {
Execute Query, error
Exception in thread "main" org.hibernate.HibernateException:
Could not instantiate regionfactory [Org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge]
(5): Need to add Ecache jar package Ehcache-1.2.3.jar
Execute Query
Exception in thread "main" java.lang.noclassdeffounderror:org/apache/commons/logging/logfactory
(6): Need to join Commons-logging-1.1.jar
Two: Cache demo
Hibernate Learning: Caching