Hibernate Level 2 Cache Configuration

Posted by taskhill on Thu, 06 Jun 2019 19:23:05 +0200

Hibernate's cache management:

Cache is a cache, and it is often the most important means of improving system performance, acting as a reservoir and buffer for data.Cache is particularly important for systems that rely heavily on data read operations.In the case of large concurrency, if each program needs to query the database directly, the performance overhead caused by them is obvious. Frequent network public opinion, Database disk read and write operations will greatly reduce the performance of the system.If you can keep a mirror of the database in local memory at this time, and you only need to get it directly from memory the next time you access it, you can obviously achieve considerable performance improvement.The difficulty in introducing the Cache mechanism is how to ensure the validity of in-memory data, otherwise the presence of dirty data will have unpredictable serious consequences for the system.Although a well-designed application can show acceptable performance without using a Cache, there is no doubt that some applications that require more reads can achieve better performance with a Cache.For applications, the Cache stores the current state of the data in the database either in memory or on disk, which is a local backup of the data.Cache is located between the database and the application, updates data from the database, and provides data to the program.

Hibernate implements a good Cache mechanism, which can help Hibernate's internal Cache to quickly improve the system's data reading performance.Cache in Hibernate can be divided into two levels: first-level Cache and second-level Cache.

Level 1 cache:

Hibernate turns on the first level cache by default, which is stored on session s and belongs to the transaction level data buffer.

Secondary Cache:

The secondary cache is in the SessionFactory, where all Sessions share the same secondary cache.It doesn't matter how the internal implementation of a secondary cache is done. It matters which correct caching strategy is used and which Cache provider is used.

Using EhCache in Hibernate:

1) Increase the configuration of the secondary cache in hibernate.cfg.xml (the maven project is placed in the resources folder)

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=GBK</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
         
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
          
        <mapping resource="com/how2java/pojo/Product.hbm.xml" />
        <mapping resource="com/how2java/pojo/Category.hbm.xml" />
        <mapping resource="com/how2java/pojo/User.hbm.xml" />
         
    </session-factory>
 
</hibernate-configuration>

2) ehcache.xml User EhCache Configuration (maven items are placed in the resources folder)

<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
</ehcache>

3) Set up hbm

For entity classes to be secondary cached, configure and increase
Transaction is only available in a managed environment.It guarantees a readable transaction isolation level and can be used for data that has a high read/write ratio and is rarely updated.
2: Read-write maintains read-write commit transaction isolation using a timestamp mechanism.This strategy can be used for data that has a high read/write ratio and is rarely updated.
3: Not strict-read-write does not guarantee database consistency between Cache and database.When using this policy, you should set a sufficient cache expiration time or dirty data may be read from the cache.This strategy can be used when some data changes very little and some of the data and databases have little impact.
4: read-only can be used when ensuring that data never changes.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="com.domain">
    <class name="Category" table="category">
         <cache usage="read-write" /><!-- Secondary Cache Configuration -->
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" column="name"/>
    </class>
     
</hibernate-mapping>

4) Test results

Using different sessions, each gets a category with id=1, accessing the database only once.Because the second fetch did not get the cache from the second session, but it got the Category cache object from the session factory.

log1
Hibernate: select category0_.id as id1_0_, category0_.name as name1_0_ from category category0_ where category0_.id=?
log2
log3
//Level 1 Cache session
System.out.println("log1");
Category c1 = (Category)session.get(Category.class, 1);
System.out.println("log2");
Category c2 = (Category)session.get(Category.class, 1);//Will not show SQL Sentence
//Submit Transaction  
session.getTransaction().commit();              
//Secondary Cache SessionFactory
Session session2 = factory.openSession();
session2.beginTransaction();
System.out.println("log3");
Category p3 = (Category) session2.get(Category.class, 1);//Will display    
session2.getTransaction().commit();

5) Notes

Packages required by maven, hibernate version 3.0, hibernate-ehcache

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>3.6.10.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>3.6.7.Final</version>
</dependency>

Topics: Java Hibernate Database Session Ehcache