hibernate的二级缓存的测试类:
package com.echo.cache2;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* 测试二级缓存
*
* @author Administrator
*
*/
public class Testhibernate {
public static void main(String[] args) {
SessionFactory sessionFactory = mySessionFactory();
// 打开会话Session1
Session session1 = sessionFactory.openSession();
// 3.开启事务
Transaction transaction1 = session1.beginTransaction();
Course c1 = (Course)session1.load(Course.class, 1);
System.out.println(c1.getCourName()+"====");
// 5.提交事务
transaction1.commit();
// 6.关闭session1
session1.close();
// 打开会话Session2
Session session2 = sessionFactory.openSession();
// 3.开启事务
Transaction transaction2 = session2.beginTransaction();
Course c2 = (Course)session2.load(Course.class, 1);
System.out.println(c2.getCourName()+"----");
// 5.提交事务
transaction2.commit();
// 6.关闭session2
session2.close();
sessionFactory.close();
}
public static SessionFactory mySessionFactory() {
SessionFactory sessionFactory = null;
// 读取并解析配置文件hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
// configuration.addClass(Course.class);
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
/*
* 读取并解析映射文件*.hbm.xml,
* 通过Configuration类的buildSessionFactory(serviceRegistry)方法实现,
* 同时该方法将返回一个会话工厂SessionFactory。
*/
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
测试结果为:
Hibernate:
select
course0_.courId as courId1_0_0_,
course0_.courTime as courTime2_0_0_,
course0_.courName as courName3_0_0_,
course0_.credit as credit4_0_0_,
course0_.stid as stid5_0_0_
from
student.course course0_
where
course0_.courId=?
张三====
张三----
原因分析:第一次从数据库select放到二级缓存。第二次直接从二级缓存中取。
如果没有使用二级缓存,则输出的测试结果为:
Hibernate:
select
course0_.courId as courId1_0_0_,
course0_.courTime as courTime2_0_0_,
course0_.courName as courName3_0_0_,
course0_.credit as credit4_0_0_,
course0_.stid as stid5_0_0_
from
student.course course0_
where
course0_.courId=?
张三====
Hibernate:
select
course0_.courId as courId1_0_0_,
course0_.courTime as courTime2_0_0_,
course0_.courName as courName3_0_0_,
course0_.credit as credit4_0_0_,
course0_.stid as stid5_0_0_
from
student.course course0_
where
course0_.courId=?
张三----