hibernate 二級緩存:(緩存的是實體對象,二級緩存是放變化不是很大的數據)
二級緩存也稱進程級的緩存或SessionFactory級的緩存,而二級緩存可以被所有的session(hibernate中的)共享二級緩存的生命周期和SessionFactory的生命周期一致,SessionFactory可以管理二級緩存
二級緩存的配置和使用:
1.將echcache.xml文件拷貝到src下, 二級緩存hibernate默認是開啟的,手動開啟
2.開啟二級緩存,修改hibernate.cfg.xml文件,
<property name=”hibernate.cache.user_second_level_cache”>true</property>
3.指定緩存產品提供商
<property name=”hibernate.cache.provider_calss”>org.hibernate.cache.EhCacheProvider</property>
4.指定那些實體類使用二級緩存(兩種方法,推薦使用第二種)
第一種:在*.hbm.xml中,在<id>之前加入
<cache usage=”read-only” />, 使用二級緩存
第二種:在hibernate.cfg.xml配置文件中,在<mapping resource=”com/Studnet.hbm.xml” />后面加上:
<class-cache class=” com.Studnet” usage=”read-only” />
二級緩存是緩存實體對象的
了解一級緩存和二級緩存的交互
測試二級緩存:
一.開啟兩個session中發出兩次load查詢(get與load一樣,同樣不會查詢數據庫),
Student sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
sessioin.close();
………..
sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
開啟兩個session中發出兩次load查詢,第一次load的時候不會去查詢數據庫,因為他是LAZY的,當使用的時候才去查詢數據庫, 第二次load的時候也不會,當使用的時候查詢數據庫,開啟了二級緩存,也不會查詢數據庫。
二.開啟兩個session,分別調用load,再使用sessionFactory清楚二級緩存
Student sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
sessioin.close();
………..
SessionFactory factory = HibernateUtil.getSessionFactory();
//factory.evict(Student.class); //清除所有Student對象
Factory.evict(Student.class,1); //清除指定id=1 的對象
sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
開啟兩個session中發出兩次load查詢,第一次load的時候不會去查詢數據庫,因為他是LAZY的,當使用的時候才去查詢數據庫, 第二次load的時候也不會,當使用的時候查詢數據庫,它要查詢數據庫,因為二級緩存中被清除了
三.一級緩存和二級緩存的交互
session.setCacheMode(CacheMode.GET); //設置成 只是從二級緩存里讀,不向二級緩存里寫數據
Student sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
sessioin.close();
………..
SessionFactory factory = HibernateUtil.getSessionFactory();
//factory.evict(Student.class); //清除所有Student對象
Factory.evict(Student.class,1); //清除指定id=1 的對象
sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
開啟兩個session中發出兩次load查詢,第一次load的時候不會去查詢數據庫,因為他是LAZY的,當使用的時候才去查詢數據庫, 第二次load的時候也不會,當使用的時候查詢數據庫,它要查詢數據庫,因為 設置了CacheMode為GET,(load設置成不能往二級緩沖中寫數據), 所以二級緩沖中沒有數據
session.setCacheMode(CacheMode.PUT); //設置成只是向二級緩存里寫數據,不讀數據
Student sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
sessioin.close();
………..
SessionFactory factory = HibernateUtil.getSessionFactory();
//factory.evict(Student.class); //清除所有Student對象
Factory.evict(Student.class,1); //清除指定id=1 的對象
sutdent = (Student)session.load(Student.class,1);
System.out.println(student.getName());
開啟兩個session中發出兩次load查詢,第一次load的時候不會去查詢數據庫,因為他是LAZY的,當使用的時候才去查詢數據庫, 第二次load的時候也不會,當使用的時候查詢數據庫,它要查詢數據庫,因為設置了CacheMode為POST,(load設置成只是向二級緩存里寫數據,不讀數據)