前提:导入ehcache-1.2.3.jar包
1.在ApplicationContext.xml中添加粗体部分
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache"></prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
2.将ehcache.xml拷贝到src下,如果没有的朋友可以来这里下载
http://download.csdn.net/detail/ahuangtaoa/4950698 免费的
3.配置cache策略(也就是告诉ehcache二级缓存的是那些对象,比如我的是Employee对象),在Employee对应的Employee.hbm.xml中添加
<cache usage="read-write"/> 一定要在<class>标签内 <id>标签前,tld约束,你懂的
4.测试:代码
private static void textEhcache() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SessionFactory factory = (SessionFactory) ac.getBean("sessionFactory");
Session session = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, 10);
System.out.println(emp.getId() + " " + emp.getName());
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
tx = null;
}
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
session = null;
}
}
System.out.println("**************");
try {
session = factory.openSession();
tx = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, 10);
System.out.println(emp.getId() + " " + emp.getName());
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
tx = null;
}
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
session = null;
}
}
// 完成一个统计,统计命中率
System.out.println(factory.getStatistics());
}