hibernate之二级缓存

本期内容:

        1、数据字典

        2、ehcache存取数据

        3、hibernate使用echcache作为二级缓存

        4、hibernate多条记录缓存

一、数据字典

1、为什么需要缓存

        拉高程序的性能

缓存又被称为非关系型数据库:数据与数据之间是不存在关系的↓

①、基于文件存储的数据库:ehcache

②、基于内存存储的数据库:redis、memcache

③、基于文档存储的数据库:mongodb

数据库存在硬盘上,存在内存上,电脑一关机,数据就不见了;

数据存在内存上读取速度快

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

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

数据字典的含义:一个项目中所有的基础数据,就是项目中所有的下拉框

数据字典解决的问题:100个下拉框需要建一百个表

数据字典的表设计:数据源表:数据源标识,数据源描述

                                数据项表:数据源标识,数据项键,数据值值

二、ehcache存储数据

将相关数据导入以及配置缓存jar包:

pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lv</groupId>
  <artifactId>lv_hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>lv_hibernate Maven Webapp</name>
  <url>http://maven.apache.org</url>
 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <junit.version>4.12</junit.version>
        <servlet.version>4.0.0</servlet.version>
        <hibernate.version>5.2.12.Final</hibernate.version>
        <mysql.driver.version>8.0.19</mysql.driver.version>

        <ehcache.version>2.10.0</ehcache.version>
        <slf4j-api.version>1.7.7</slf4j-api.version>
        <log4j-api.version>2.9.1</log4j-api.version>
    </properties>
  
   <dependencies>
    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>
        
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>${ehcache.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        
        <!-- slf4j核心包 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j-api.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--用于与slf4j保持桥接 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${log4j-api.version}</version>
        </dependency>

        <!--核心log4j2jar包 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j-api.version}</version>
        </dependency>
  </dependencies>
  <build>
    <finalName>lv_hibernate</finalName>
     <plugins>
        <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
    </plugins>
  </build>
</project>
 

1、利用ehcache访问值

怎么使用缓存:
 *     1、优先从缓存中获取对应数据
 *     2、如果获取到了,那么直接返回
 *     3、没有获取到,那么查询数据库,将数据库对应的数据放入缓存,再返回

EhcacheDemo1:

package lv.com.four.test;

import java.util.HashMap;
import java.util.Map;

/**
 * 利用map集合简易实现缓存原理

 * @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——数据库中得到的
         * zs——缓存中得到的
         */

                    }
}

 

ehcache的三个核心接口:

        CacheManager:缓存管理器
        Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
        Element:单条缓存数据的组成单位

2、演示利用ehcache值:

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="1"
           overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

EhcacheDemo2:

package lv.com.four.test;

import lv.com.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.one.entity.User", 11, "zhangsan");
        System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
    }
}

结果呈现,存取数据:

三、hibernate使用echcache作为二级缓存

 一级缓存

        又称为session级别的缓存

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();
    }

 二级缓存:

        sessionFactory级别的缓存

开启二级缓存:

        ①、在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:User.hbm.xml文件中name要与region内的路径要一样,并且和ehcache中的name的路径相同

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="lv.com.one.entity.User" table="t_hibernate_user">
        <cache usage="read-write" region="lv.com.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="lv.com.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);
        
    }

呈现结果,出现了一次SQL语句,用到了二级缓存: 

 

 四、hibernate多条记录缓存

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

我们可以设置Cacheable使用缓存

package lv.com.four.test;

import java.util.List;

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

import lv.com.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();
    }
}
 

呈现结果:就一条SQL语句

本期内容结束~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值