1.要实现二级缓存,需另加以下jar包:
ehcache-core-2.4.3.jar、hibernate-core-4.2.3.Final.jar、slf4j-api-1.6.6.jar
2.需要更改配置文件
hibernate.cfg.xml
/p>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql://127.0.0.1:3306/hibernate_db
root
beanGou
1
org.hibernate.dialect.MySQLDialect
thread
org.hibernate.cache.ehcache.EhCacheRegionFactory
ehcache2.xml
true
true
true
update
如果要给某个类设置二级缓存,则相应的改其配置文件,如
Employee.hbm.xml
/p>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
3.测试代码
@Test
public void get() {
Session session = HibernateUtil.getSession();
Employee employee = (Employee) session.get(Employee.class, 1);
employee = (Employee) session.get(Employee.class, 1);
System.out.println(employee.getName());
session.evict(employee);
employee = (Employee) session.get(Employee.class, 1);
session.close();
Statistics statistics = HibernateUtil.getSessionFactory().getStatistics();
System.out.println(statistics);
System.out.println("命中数:" + statistics.getSecondLevelCacheHitCount());
System.out.println("错过数:" + statistics.getSecondLevelCacheMissCount());
System.out.println("放入数:" + statistics.getSecondLevelCachePutCount());
}
注:增加了HibernateUtil类以及getSessionFactory方法
package com.sinoi.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory factory;
private static Session session;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
if (factory == null) {
factory = new Configuration().configure().buildSessionFactory();
}
return factory;
}
public static Session getSession() {
if (session == null) {
return getSessionFactory().openSession();
} else {
return session;
}
}
}