Danial7777777

导航

hibernate二级缓存整合

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

  <!-- 磁盘缓存位置 -->
  <diskStore path="java.io.tmpdir/ehcache" />

  <!-- 默认缓存 -->
   <defaultCache
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU"
          >
  </defaultCache>
  
  <!-- helloworld缓存 -->
  <cache name="HelloWorldCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="true"
         memoryStoreEvictionPolicy="LRU"/>

  <cache name="UserCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="1800"
         timeToLiveSeconds="1800"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql:///hibernate</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>

        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- 开启二级缓存 -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!-- 二级缓存的提供类 在hibernate4.0版本以后我们都是配置这个属性来指定二级缓存的提供类 -->
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <!-- 二级缓存配置文件的位置 -->
        <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>

        <mapping resource="com/hello/User.hbm.xml" />
        <mapping resource="com/hello/Account.hbm.xml" />
        <mapping resource="com/manytomany/Student.hbm.xml" />
        <mapping resource="com/manytomany/Teacher.hbm.xml" />
        <mapping resource="com/ehcache/User.hbm.xml" />
    </session-factory>


</hibernate-configuration>
<?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.ehcache">
    <!-- name属性:哪个类 table属性:对应哪个表,如果不写,默认的表名就是类的简单名称 -->
    <class name="User" table="tt_user">
        <cache usage="read-only" />
        <id name="id">
            <generator class="native" />
        </id>
        <property name="name" not-null="true" />
    </class>
</hibernate-mapping>
package com.ehcache;


public class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

 

package com.ehcache;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.ehcache.User;

public class HelloTest {

    private static SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration()
        .configure() // 读取配置文件
        .buildSessionFactory();
    }

    // 根据配置生成表结构
    @Test
    public void test() {
        //hibernate 5.0
        Configuration conf = new Configuration().configure();//1、读取配置文件
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    }

    //测试hibernate二级缓存配置,session关闭之后是否能读取
    @Test
    public void hello(){
        Session session=sessionFactory.openSession();
        User user = session.get(User.class,1);
        System.out.println(user.getName()+"===================");
        session.clear();//清除缓存
        session.close();
        System.out.println("=================================");
        Session session2=sessionFactory.openSession();
        User user2 = session2.get(User.class,1 );
        System.out.println(user.getName()+"===================");
         /**
         * 因为设置了二级缓存为read-only,所以不能对其进行修改
         */
        session2.beginTransaction();
        user2.setName("aaa");
        session2.getTransaction().commit();
        session2.close();
    }

        /**
     *  注意:二级缓存中缓存的仅仅是对象,而下面这里只保存了姓名和性别两个字段,所以 不会被加载到二级缓存里面
     */
    @Test
    public void hello2(){
        
        Session session=sessionFactory.openSession();
        Query query = session.createQuery("select id,name from User where id=1");
        List list = query.list();
        session.close();
        Session session2=sessionFactory.openSession();
        /**
         * 由于二级缓存缓存的是对象,所以此时会发出两条sql
         */
        User user = session2.get(User.class, 1);
        System.out.println(user.getName());
        session.close();
    }

}

 

posted on 2018-07-22 00:59  Danial7777777  阅读(158)  评论(0编辑  收藏  举报