hibernate 一级缓存、二级缓存

一级缓存:——session一旦关掉就没有了。
使用 load和get加载对象的时候,会自动加载到缓存,读取的也会读缓存。

public void huancun(){
        Session session=null;
        try{
            session=HibernateUtil.getSession();
          
            Info data1=session.get(Info.class, "p003");
            Info data2 =session.get(Info.class, "p003");
            System.out.println(data1 == data2);
            
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }

生成了一条查询语句,返回的结果为true   

第一次get()生成了语句,在数据库中生成了查询,第二次,hibernate会检索缓存中是否有该条数据,如果有,直接从缓存中取出该条数据,不再去数据库中查询

使用hql查询多条数据库,如果使用getResultList()默认是无法放到缓存中的。使用iterator()可以用在缓存中。

public void huancun(){
        Session session=null;
        try{
            session=HibernateUtil.getSession();
            //默认是无法放到缓存中的
            List<Info> list1 = session.createQuery("from Info").getResultList();
            List<Info> list2= session.createQuery("from Info").getResultList();
    
            System.out.println(list1 == list2);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }

生成结果如下

说明并没有进行缓存,两次查询出的对象也并不是同一个对象

使用iterator迭代器,第一次查询会生成缓存,第二次查询时会先检索缓存中是否存在需要的数据

public void huancun(){
        Session session=null;
        try{
            session=HibernateUtil.getSession();

       //iterator()迭代器
            Iterator<Info> list1=session.createQuery("from Info").iterate();
            while(list1.hasNext()){
                System.out.println(list1.next().getName());
            }
            Iterator<Info> list2 = session.createQuery("from Info").iterate();
            while(list2.hasNext()){
                System.out.println(list2.next().getName());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }

生成结果如下

很明显的能看出,第一次查询时生成了sql语句,第二次没有,直接从缓存中将数据取出

Hibernate二级缓存:需要扩展外部插件。SessionFactory内的缓存。Session关了后,只要SessionFactory没有close,还可以使用缓存。

插件需要的3个jar包:

2.在hibernate.cfg.xml中配置,启动二级缓存

<?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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        
        <!-- 配置缓存 -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheMessageLogger</property>
        <property name="hibernate.cache.use_query_cache">true</property>
        <!-- 结束 -->
        
        <mapping resource="com/maya/model/Family.hbm.xml"/>
        <mapping resource="com/maya/model/Info.hbm.xml"/>
        <mapping resource="com/maya/model/Nation.hbm.xml"/>
        <mapping resource="com/maya/model/Title.hbm.xml"/>
        <mapping resource="com/maya/model/Work.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3.把ehcache.xml配置文件复制过来,放到hibernate框架生成的实体类映射文件同一文件夹下

4.在实体类的映射文件中,配置缓存

<?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">
<!-- Generated 2017-3-11 9:29:47 by Hibernate Tools 5.2.0.CR1 -->
<hibernate-mapping>
    <class name="com.maya.model.Info" table="info" catalog="mydb" optimistic-lock="version">
    <!-- <cache usage="read-write"/> 这句话一定要放在class下面的最前面  -->
     <cache usage="read-write"/>
     
        <id name="code" type="string">
            <column name="Code" length="50" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="Name" length="50" />
        </property>
        <property name="sex" type="java.lang.Boolean">
            <column name="Sex" />
        </property>
        <property name="nation" type="string">
            <column name="Nation" length="50" />
        </property>
        <property name="birthday" type="timestamp">
            <column name="Birthday" length="19" />
        </property>
    </class>
</hibernate-mapping>

配置完成后,如果使用load或get的时候,不需要其它操作,直接使用的二缓存,中间session关闭也没关系

原文地址:https://www.cnblogs.com/zhaotiancheng/p/6537707.html