0
点赞
收藏
分享

微信扫一扫

hibernate整合二级缓存


导入jar包

backport-util-concurrent.jar
commons-logging.jar
ehcache-1.5.0.jar

配置hibernate.cfg.xml

<!--开启二级缓存-->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--配置供应商店-->
<property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider</property>

配置类和集合缓存

dtd约束 配置在mapping下

<!--        配置集合缓存-->
<collection-cache collection="org.ccit.com.domain.Customer.orders" usage="read-only"></collection-cache>
<!-- 配置类缓存-->
<class-cache class="org.ccit.com.domain.Customer" usage="read-only"></class-cache>
<class-cache class="org.ccit.com.domain.Order" usage="read-only"></class-cache>

在src目录下 添加ehcache.xml文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>

测试

import org.ccit.com.domain.Customer;
import org.ccit.com.uitls.HibernateUtils;
import org.hibernate.Session;
import org.junit.Test;

/**
* @program: Hibernate_01
* @description
* @author: LIANG
* @create: 2021-03-25 09:54
**/
public class HibernateTest12ehcache {
@Test
public void demo01(){
Session session = HibernateUtils.openSession();
session.getTransaction().begin();

//执行select后 会将数据存入一级缓存和二级缓存 清空一级缓存后 取数据仍然不需要执行sql语句
Customer customer = (Customer)session.get(Customer.class,1);
System.out.println(customer);
session.clear();

Customer customer1 = (Customer)session.get(Customer.class, 1);
System.out.println(customer);

session.getTransaction().commit();
session.close();

//其他缓存也可以不执行sql语句从二级缓存中取出数据
Session session1 = HibernateUtils.openSession();
session1.getTransaction().begin();

Customer customer2 = (Customer)session1.get(Customer.class, 1);
System.out.println(customer2);
session1.getTransaction().commit();
session1.close();
}
}

只执行一次sql

hibernate整合二级缓存_hibernate


举报

相关推荐

0 条评论