package com.qjmotor.hibernate;
import org.hibernate.CacheMode;
import org.hibernate.Session;
import junit.framework.TestCase;
public class CacheTest extends TestCase {
/**
* 开启二级缓存
*
* 两个session中,缓存数据
*/
public void testCache1(){
Session session=null;
try{
session=HibernateUtils.getSession();
session.beginTransaction();
//发出Sql语句
Student student = (Student)session.get(Student.class, 1);
System.out.println("student.getName()=" + student.getName());
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
try{
session=HibernateUtils.getSession();
session.beginTransaction();
//不会发出查询语句,二级缓存是进程级的,不同session共享二级缓存
Student student = (Student)session.get(Student.class, 1);
System.out.println("student.getName()=" + student.getName());
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
/**
* 开启二级缓存
*
* 两个session中,缓存数据
*/
public void testCache2(){
Session session=null;
try{
session=HibernateUtils.getSession();
session.beginTransaction();
//发出Sql语句
Student student = (Student)session.load(Student.class, 1);
System.out.println("student.getName()=" + student.getName());
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
try{
session=HibernateUtils.getSession();
session.beginTransaction();
//不会发出查询语句,二级缓存是进程级的,不同session共享二级缓存
Student student = (Student)session.load(Student.class, 1);
System.out.println("student.getName()=" + student.getName());
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
}
testCache1()结果
14:45:06,593 WARN CacheFactory:43 - read-only cache configured for mutable class: com.qjmotor.hibernate.Student
14:45:06,593 WARN EhCacheProvider:86 - Could not find configuration [com.qjmotor.hibernate.Student]; using defaults.
Hibernate: select student0_.id as id1_0_, student0_.name as name1_0_, student0_.class_id as class3_1_0_ from t_student student0_ where student0_.id=?
student.getName()=李四
student.getName()=李四
到此处说明不同session是共享二级缓存的
换种测试方式,testCache1()在第二个try出设置断点,目的是待student装入二级缓存后,执行testCache2()
testCache2()结果
Hibernate: select student0_.id as id1_0_, student0_.name as name1_0_, student0_.class_id as class3_1_0_ from t_student student0_ where student0_.id=?
student.getName()=李四
student.getName()=李四
为什么testCache2()不利用二级缓存取数据呢?