hibernate之二级缓存

一、认识缓存

1、为什么需要缓存        

拉高程序的性能

2、关系数据库与非关系型数据库的区别

关系型数据库

含义:数据与数据之间存在关系的数据库 mysql Oracle SQLserver

非关系型数据库

含义:数据与数据之间是不存在关系的 ——以键值对的形式存在

3、什么样的数据需要缓存

很少被修改或者根本不修改的数据——数据字典

4、ehcache是什么

ehcache是现在最流行的纯java开源缓存的框架,配置简单,结构清晰,功能强大

5、ehcache的特点

5.1够快

5.2够简单

5.3够袖珍

5.4够轻量

5.5好扩展

5.6监听器

5.7分布式缓存

6、使用ehcache的使用

1. 导入相关依赖、

     <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache</artifactId>
          <version>2.10.0</version>
      </dependency>

  
2. 核心接口

  CacheManager:缓存管理器

    Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的质所有cache都实现             

Ehcache接口

     Element:单条缓存数据的组成单位


3. src:ehcache.xml

7、hibernate缓存

  一级缓存 session

二级缓存 sessionFactory可插拔式

二、数据字典

1、数据字典的含义

一个项目中所有的基础数据,就是项目中的所有下拉框

解决的问题:避免了动不动就建很多表的情况

三、eacache存取数据

导入需要的jar包

 EhcacheDemo1

package com.zking.four.test;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 利用map集合简易实现缓存原理
 * 
 * 怎么使用缓存
 * 注意:只要使用缓存,默认缓存中就有数据
 * 1.优先从缓存中获取对应数据
 * 2.如果获取到了,那么直接返回
 * 3.没有获取到,那么查询数据库,将数据库对应的数据放入缓存,再返回
 * @author Administrator
 *
 */
public class EhcacheDemo1 {
	static Map<String, Object> cache = new HashMap<String, Object>();
	static Object getValue(String key) {
		Object value = cache.get(key);
		if(value == null) {
			System.out.println("hello zs");//从数据库中读取数据
			cache.put(key, new String[] {"zs"});
			return cache.get(key);
		}
		return value;
	}
	
	public static void main(String[] args) {
		System.out.println(getValue("sname"));
		System.out.println(getValue("sname"));
	}
}

 运行结果

 原因:后面两个乱码了是因为是集合

第一个输出语句输出的结果为 hello zs/[zs]

原因:进入方法会先从ehcache中拿值,可ehcache中没有值所以就去数据库读取数据

if判断里面输出 hello zs ,然后返回值返回zs

第二个输出语句输出的结果为 [zs]

原因:因为已经有值了,所以直接返回
 

导入xml文件

 ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
    <!--path:指定在硬盘上存储对象的路径-->
    <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="D://xxx"/>
 
 
    <!--defaultCache:默认的管理策略-->
    <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
    <!--maxElementsInMemory:在内存中缓存的element的最大数目-->
    <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
    <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
    <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
    <!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
    <!--FIFO:first in first out (先进先出)-->
    <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
    <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
 
 
    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
    <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

EhcacheDemo2

package com.zking.four.test;
 
import com.zking.four.util.EhcacheUtil;
 
/**
 * 演示利用缓存存储数据
 * @author Administrator
 *
 */
public class EhcacheDemo2 {
	public static void main(String[] args) {
		System.out.println(System.getProperty("java.io.tmpdir"));
		EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
		System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
	}
}

存储数据

 四、hibernate使用ehcache作为二级缓存

EhcacheDemo3

/**
     * 同一个session,sql语句只生成一次,这里用到了一级缓存
     */
    @Test
    public void test1() {
        Session session = SessionFactoryUtil.getSession();
        Transaction transaction = session.beginTransaction();
        
        User user = session.get(User.class, 7);
        System.out.println(user);
        User user2 = session.get(User.class, 7);
        System.out.println(user2);
        User user3 = session.get(User.class, 7);
        System.out.println(user3);
        
        transaction.commit();
        session.close();
    }

 二级缓存

在hibernate.cfg.xml文件中进行配置

<!-- 开启二级缓存 -->
      <property name="hibernate.cache.use_second_level_cache">true</property>
      <!-- 开启查询缓存 -->
      <property name="hibernate.cache.use_query_cache">true</property>
      <!-- EhCache驱动 -->
      <!-- 注意:此处必须用hibernate的5.2.12.Final 版本 -->
      <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 
    <class name="lxy.com.one.entity.User" table="t_hibernate_user">
        <cache usage="read-write" region="com.lxy.one.entity.User"/>
        
        <id name="id" type="java.lang.Integer" column="id">
            <generator class="assigned" />
        </id>
        <property name="userName" type="java.lang.String" column="user_name">
        </property>
        <property name="userPwd" type="java.lang.String" column="user_pwd">
        </property>
        <property name="realName" type="java.lang.String" column="real_name">
        </property>
        <property name="sex" type="java.lang.String" column="sex">
        </property>
        <property name="birthday" type="java.sql.Date" column="birthday">
        </property>
        <property insert="false" update="false" name="createDatetime"
            type="java.sql.Timestamp" column="create_datetime">
        </property>
        <property name="remark" type="java.lang.String" column="remark">
        </property>
    </class>
</hibernate-mapping>

ehcache.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
       <diskStore path="D://xxx"/>

      <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>

    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
    <cache name="com.lxy.one.entity.User" eternal="false" maxElementsInMemory="1"
           overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

测试

@Test
    public void test2() {
        UserDao userDao  = new UserDao();
        User u = new User();
        u.setId(7);
        User user = userDao.get(u);
        System.out.println(user);
        User user2 = userDao.get(u);
        System.out.println(user2);
        User user3 = userDao.get(u);
        System.out.println(user3);
        
    }

运行结果 

 五、hibernate多条记录缓存

hibernate二级缓存不会同时缓存多条数据

EhcacheDemo4

package com.zking.four.test;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.zking.two.util.SessionFactoryUtil;

/**
 * hibernate二级缓存不会同时缓存多条数据
 * @author Administrator
 *
 */
public class EhcacheDemo4 {
    public static void main(String[] args) {
        Session session = SessionFactoryUtil.getSession();
        Transaction transaction = session.beginTransaction();
        
        Query query = session.createQuery("from User");
        query.setCacheable(true);
        List list = query.list();
        System.out.println(list);
        List list2 = query.list();
        System.out.println(list2);
        List list3 = query.list();
        System.out.println(list3);
        
         transaction.commit();
        session.close();
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欣宇不会敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值