hibernate4 二级缓存demo实例

来源:互联网 发布:中控考勤机软件 编辑:程序博客网 时间:2024/05/17 02:48

hibernate使用版本是:hibernate-release-4.2.5.Final

需要的jar包:hibernate-release-4.2.5.Final\lib\required下所有jar包

ehcache  jar包:hibernate-release-4.2.5.Final\lib\optional\ehcache下所有包

junit:junit-4.10.jar和mysql-connector-java-5.1.15-bin.jar

注:hibernate 4.2.5版本ehcache缓存不依赖commons-logging-1.1.1.jar,需要的是slf4j-api-1.6.1.jar

项目结构如下
 

HibernateUtil

package com.action;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;public class HibernateUtil { private static SessionFactory sessionFactory;             /**      * @return 获取会话工厂       */        public static SessionFactory getSessionFactory(){                  //第一步:读取Hibernate的配置文件  hibernamte.cfg.xml文件          Configuration con=new Configuration().configure();                    //第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息          ServiceRegistryBuilder regbulider=new ServiceRegistryBuilder().applySettings(con.getProperties());                    //创建注册服务          ServiceRegistry reg=regbulider.buildServiceRegistry();                    //第三步:创建会话工厂          SessionFactory sessionFactory=con.buildSessionFactory(reg);                    return sessionFactory;        }               /**       * @return 获取会话对象       */      public static Session getCurrentSession(){return getSessionFactory().openSession();  }  public static void closeSession() {// TODO Auto-generated method stub }}


 

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>          <!-- Database connection settings -->          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>          <property name="connection.url">jdbc:mysql://127.0.0.1:3306/HibernateCache</property>          <property name="connection.username">root</property>          <property name="connection.password">root</property>                <!-- JDBC connection pool (use the built-in) -->          <property name="connection.pool_size">1</property>                <!-- SQL dialect -->          <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>                <!-- Enable Hibernate's automatic session context management -->          <property name="current_session_context_class">thread</property>                <!-- Disable the second-level cache -->          <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>         -->                <!-- 配置二级缓存 -->          <property name="hibernate.cache.use_second_level_cache">true</property>          <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>          <!-- hibernate3的二级缓存配置 -->          <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->                <!-- 开启查询缓存 -->          <property name="hibernate.cache.use_query_cache">true</property>                    <!-- Echo all executed SQL to stdout -->        <property name="show_sql">true</property>                <!-- Drop and re-create the database schema on startup -->        <property name="hbm2ddl.auto">update</property>        <mapping class="com.bean.User" />            </session-factory>    </hibernate-configuration>


注意:hibernate4和hibernate3配置不一样,hibernate4是

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  


 

而hibernate3的配置是

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  

(此处有一个疑问是:hibernate4的官方文档中,已经把class改了,但是属性名称没有改,还是hibernate.cache.provider_class,不是上面的hibernate.cache.region.factory_class,但是写成hibernate.cache.provider_class会报错误)

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:/ehcache"></diskStore>          <!--          默认设置          maxElementsInMemory : 在內存中最大緩存的对象数量。        eternal : 缓存的对象是否永远不变。          timeToIdleSeconds :可以操作对象的时间。          timeToLiveSeconds :缓存中对象的生命周期,时间到后查询数据会从数据库中读取。          overflowToDisk :内存满了,是否要缓存到硬盘。      -->      <defaultCache maxElementsInMemory="1000" eternal="false"          timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />             <!--          指定缓存的对象。          下面出现的的属性覆盖上面出现的,没出现的继承上面的。    -->     <cache name="userCache" eternal="false" maxElementsInMemory="1000"          overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"          timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />      </ehcache>


 

User实体类

package com.bean;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;@Entity@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)  public class User{    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)      private int id;      private String name;      private int age;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;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}      }


UserTest测试类(JUnit):

package com.test;import org.hibernate.Session;import org.junit.Test;import com.action.HibernateUtil2;import com.bean.User;public class UserTest {     @Test      public void testEhcache() {          Session session = HibernateUtil.getCurrentSession();          session.beginTransaction();        User u1 = (User) session.load(User.class, 3);          System.out.println(u1.getName());          session.getTransaction().commit();          session.close();          Session session2 = HibernateUtil.getSessionFactory().openSession();                  session2.beginTransaction();          User u2 = (User) session2.load(User.class, 3);          System.out.println(u2.getName());          session2.getTransaction().commit();          session2.close();    }  }


结果:

Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.name as name3_0_0_ from User user0_ where user0_.id=?  zhangsan  zhangsan  



 

0 0
原创粉丝点击