`
dreamoftch
  • 浏览: 485450 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Hibernate和EhCache整合

阅读更多

 

 首先是pom.xml,这里面有一些dependency是没有用的,都贴上吧。

<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.tch.test</groupId>
  <artifactId>simple-web</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>simple-web Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit-version>4.11</junit-version>
    <spring-version>3.2.6.RELEASE</spring-version>
    <hiberante-version>3.6.10.Final</hiberante-version>
    <struts2-version>2.3.16</struts2-version>
    <mysql-version>5.1.28</mysql-version>
    <log4j-version>1.2.17</log4j-version>
    <slf4j-version>1.7.5</slf4j-version>
    <aspectj-version>1.7.4</aspectj-version>
    <postgresql-version>9.1-901-1.jdbc4</postgresql-version>
    <ehcacheVersion>2.6.11</ehcacheVersion>
  </properties>

  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
    <!-- spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <!-- spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <!-- hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hiberante-version}</version>
    </dependency>
    <!-- hibernate-proxool -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-proxool</artifactId>
      <version>${hiberante-version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>${hiberante-version}</version>
    </dependency>
    <!-- struts2 -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>${struts2-version}</version>
    </dependency>
    <!-- struts2-spring-plugin -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>${struts2-version}</version>
    </dependency>
    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql-version}</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j-version}</version>
    </dependency>
    <!-- slf4j-log4j -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j-version}</version>
    </dependency>
    <!-- aspectjrt -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj-version}</version>
    </dependency>
    <!-- aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj-version}</version>
    </dependency>
    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>${postgresql-version}</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>${ehcacheVersion}</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>simple-web</finalName>
  </build>
</project>

 

 

hibernate.cfg.xml:

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.password">postgres</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>

    <!-- For singleton factory -->
    <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property> -->

    <!-- enable second level cache and query cache -->
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
    <mapping class="com.tch.test.entity.Employee" />
  </session-factory>
</hibernate-configuration>

 

ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
    monitoring="autodetect" dynamicConfig="true">
 
    <diskStore path="java.io.tmpdir/ehcache" />
 
    <defaultCache maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
        maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU" statistics="true">
        <persistence strategy="localTempSwap" />
    </defaultCache>
 
    <cache name="query.Employee" maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="5" timeToLiveSeconds="10">
        <persistence strategy="localTempSwap" />
    </cache>
    
    
 
    <cache name="org.hibernate.cache.internal.StandardQueryCache"
        maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
        <persistence strategy="localTempSwap" />
    </cache>
 
    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
        maxEntriesLocalHeap="5000" eternal="true">
        <persistence strategy="localTempSwap" />
    </cache>
</ehcache>

 

log4j.properties:

log4j.rootLogger=error,CONSOLE

###################
# Console Appender
###################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p (%c:%L) - %m%n


log4j.logger.org.hibernate.cache=debug

 

 

实体类:

package com.tch.test.entity;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
 
@Entity
@Table(name = "EMPLOYEE")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Employee {
 
    @Id
    @GeneratedValue
    @Column(name = "emp_id")
    private long id;
 
    @Column(name = "emp_name")
    private String name;
 
    @Column(name = "emp_salary")
    private double salary;
 
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
    
    public Employee() {
        super();
    }

    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }
 
}

 

 

HibernateUtil工具类:

package com.tch.test.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    private static SessionFactory sessionFactory;
     
    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
             
            SessionFactory sessionFactory = configuration.buildSessionFactory();
             
            return sessionFactory;
        }
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }
     
    public static SessionFactory getSessionFactory() {
        if(sessionFactory == null) sessionFactory = buildSessionFactory();
        return sessionFactory;
    }
}

 

 

测试类:

 

package com.tch.test;
 
import java.util.Arrays;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.stat.Statistics;

import com.tch.test.entity.Employee;
import com.tch.test.util.HibernateUtil;
 
public class HibernateEHCacheMain {
 
    public static void main(String[] args) {
//        saveData(HibernateUtil.getSessionFactory());
        
//        Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
//        stats.setStatisticsEnabled(true);
        
        getData(HibernateUtil.getSessionFactory());
        
//        printStats(stats, 1);
        
        getData(HibernateUtil.getSessionFactory());
        
//        printStats(stats, 2);
        
        getData(HibernateUtil.getSessionFactory());
        
//        printStats(stats, 3);
        
        getData(HibernateUtil.getSessionFactory());
        
//        printStats(stats, 4);
        
        HibernateUtil.getSessionFactory().close();
    }
    
    private static void getData(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        System.err.println("begin get data ...");
//        session.createQuery("from Employee").list();
//        session.createQuery("from Employee").setCacheable(true).setCacheRegion("query.Employee").list();
//        ((Employee) session.load(Employee.class, 34l)).getName();
//        session.createQuery("from Employee").list();
//        System.out.println(session.createQuery("from Employee").setCacheable(true).list());
        session.createQuery("from Employee").setCacheable(true).list();
        
        transaction.commit();
    }
 
    private static void saveData(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        
        Employee employee1 = new Employee("employee 1", 1000);
        
        Employee employee2 = new Employee("employee 2", 1000);
        
        Employee employee3 = new Employee("employee 3", 1000);
        
        Employee employee4 = new Employee("employee 4", 1000);
        
        session.save(employee1);
        session.save(employee2);
        session.save(employee3);
        session.save(employee4);
        
        transaction.commit();
    }

    private static void printStats(Statistics stats, int i) {
        System.out.println("***** " + i + " *****");
        System.out.println("Fetch Count="
                + stats.getEntityFetchCount());
        System.out.println("Second Level Hit Count="
                + stats.getSecondLevelCacheHitCount());
        System.out
                .println("Second Level Miss Count="
                        + stats
                                .getSecondLevelCacheMissCount());
        System.out.println("Second Level Put Count="
                + stats.getSecondLevelCachePutCount());
    }
 
}

 

首先调用saveData()插入数据,然后调用getData()查询数据(是在不同的session中),会看的只有一条sql执行了,其他的都是从ehcache的缓存中读取的(根据log中的信息:caching query results in region: org.hibernate.cache.StandardQueryCache; timestamp=5862689108340736可以知道)

 

就说明二级缓存生效了。。。。

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics