Cache Mechanism
The cache is between applications and physical data sources. It is used to reduce the frequency of applications accessing physical data sources and improve the running performance of applications. Data in the cache is the replication of data in the physical data source. during runtime, the application reads and writes data from the cache. Data in the cache and the physical data source will be synchronized at a specific time or event.
Hibernate cache includes Session cache and SessionFactory cache, which become the first cache and second-level cache. Both cache are on the persistence layer and store copies of database data.
Level 1 Cache
The lifecycle of a first-level cache is very short and consistent with that of a session. A first-level cache is also called a session-level cache or transaction-level cache. In the same Session, it caches entity objects, the load/get/iterate and save methods support level-1 caching. (After saving in the same Session, load does not issue SQL statements.) However, level-1 caching does not cache common attributes.
When adding a large volume of data in a level-1 cache, pay attention to cache overflow. cache should be cleared in a timely manner for each number of data records added. The sample code is as follows:
[Java] view plaincopy
/**
* Add a large volume of data
*/
Public void testCache7 (){
Session session = null;
Try {
Session = HibernateUtils. getSession ();
Session. beginTransaction ();
For (int I = 0; I <100; I ++ ){
Student student = new Student ();
Student. setName ("James" + I );
Session. save (student );
// Every 20 updates
If (I % 20 = 0 ){
Session. flush ();
// Clear the cached content
Session. clear ();
}
}
Session. getTransaction (). commit ();
} Catch (Exception e ){
E. printStackTrace ();
Session. getTransaction (). rollback ();
} Finally {
HibernateUtils. closeSession (session );
}
}
Level 2 Cache
The second-level cache is also called the process-level cache or SessionFactory-level cache. The second-level cache can be shared by all sessions. The second-level cache has the same lifecycle as SessionFactory, sessionFactory can manage second-level caches. Second-level caches generally use third-party cache products. The Hibernate documentation recommends Hashtable (inside Hibernate for testing only), EHCache, OSCache, SwarmCache, and JBossTreeCache.
Taking EHCache as an example, configure and use the secondary cache:
1. Copy the ehcache. xml file to src;
2. Add the cache product provider <propertyname = "hibernate. cache. provider_class"> org. hibernate. cache. EhCacheProvider </property> to the hibernate. cfg. xml file;
3. enable secondary cache, which is also its default configuration <propertyname = "hibernate. cache. use_second_level_cache"> true </property>;
4. Specify which object classes use the second-level cache
You can use the <cache> label in the ing file or specify it in the hibernate. cfg. xml file. Note that the read-only and read-write policies are usually used;
Cache principle: data that is read much more than written is usually cached.
In the interaction between a level-1 cache and a level-2 cache, you can use the method session. setCacheMode (CacheMode. IGNORE) in the level-1 cache to disable data from being placed in the level-2 cache. When adding a large volume of data in the first-level cache, the first-level cache should be cleared at any time to prevent cache overflow. However, if the second-level cache is configured, if the second-level cache is not prohibited, it will also cause cache overflow and errors, therefore, interaction between the first-level cache and the second-level cache must be disabled.
Query Cache
The query cache is the result set of the cache common attribute. You can cache the id of the result set of the object and query the cache lifecycle. When the associated table is modified, the query cache lifecycle ends, the query cache has nothing to do with the session lifecycle and can be performed across sessions. Query cache only applies to query. list (). query. iterate () does not use query cache to query common attributes.
Query cache configuration and usage:
1. Modify the hibernate. cfg. xml file to enable the query cache. The default value is false. <propertyname = "hibernate. cache. use_query_cache"> true </property>
2. query. setCacheable (true) must be enabled in the program)
Lock Mechanism
In fact, there are some problems with writing locks into Hibernate optimization. Locking is a huge loss of performance, but in some cases we have to consider locking out of solving the concurrency problem, there is a reflection on performance optimization. Here we can choose pessimistic locks and optimistic locks, which have different effects on performance. Therefore, rational locks can also improve the performance of Hibernate.
Pessimistic lock
Pessimistic locks are usually implemented by the database mechanism. Data is locked throughout the process (during query) as long as the transaction is not released (commit/rollback ), no user can view or modify it.
You only need to add the third parameter LockMode. UPGRADE to the load method. Also:
LockMode. NONE: No lock mechanism.
LockMode. WRITE: Hibernate will automatically obtain the Insert and Update records.
LockMode. READ: Hibernate automatically obtains the data when reading the record.
The above three lock mechanisms are generally used internally by Hibernate. For example, in order to ensure that objects in the Update process are not modified by the outside world, Hibernate will automatically add the WRITE lock to the target object in the implementation of the save method.
LockMode. UPGRADE: use the database's forupdate clause to lock.
LockMode. UPGRADE_NOWAIT: the specific implementation of Oracle, which uses the Oracle for update nowait clause to implement locking.
Optimistic lock
Optimistic locks are mostly implemented using the version method. Generally, a version field is added to the database to read the version when reading data, when saving data, determine whether the version value is smaller than the version value in the database. If it is smaller than the version value, it is not updated. Otherwise, update the version.
In Hibernate, the class label is described by the attribute optimistic-lock = "version". The optional value of the optimistic-lock attribute is as follows:
None: No optimistic lock.
Version: Optimistic Locking is implemented through the version mechanism.
Dirty: checks the changed attributes to implement optimistic locks.
All: Optimistic lock is implemented by checking all attributes.
Among them, the optimistic lock mechanism implemented through version is the optimistic lock implementation officially recommended by Hibernate. It is also in Hibernate. Currently, it is only effective when the data object is modified from the Session.
Author: StubbornPotatoes