hibernate——快取
阿新 • • 發佈:2018-11-21
/** * Created by Administrator on 2018/11/16 0016. * 一級快取 Session * 二級快取 SessionFactory * 查詢快取 createQuery */
一級快取
get,load方法自動從一級快取中查詢,如果存在快取物件,直接使用
@Test public void firstLevel(){ Session session = HibernateUtil.getCurrentSession(); Province p = session.get(Province.class,1); Province p1 = session.get(Province.class,1); HibernateUtil.close(session); }
二級快取
hibernate.cfg.xml配置
<!--使用二級快取--> <property name="hibernate.cache.use_second_level_cache">true</property> <!--配置二級快取服務商--> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
@Test public void sencondLevel(){ Session session = HibernateUtil.getCurrentSession(); Province p = session.get(Province.class,1); HibernateUtil.close(session); Session session1 = HibernateUtil.getCurrentSession(); Province p1 = session1.get(Province.class,1); session1.beginTransaction(); p1.setName("aaaaa"); session1.saveOrUpdate(p1); session1.getTransaction().commit(); HibernateUtil.close(session1); }
查詢快取
hibernate.cfg.xml配置
<!--使用查詢快取-->
<property name="cache.use_query_cache">true</property>
@Test
public void queryCache(){
Session session = HibernateUtil.getCurrentSession();
List<Province> provinceList = session.createQuery("from Province ").setCacheable(true).list();
HibernateUtil.close(session);
Session session1 = HibernateUtil.getCurrentSession();
List<Province> provinceList1 = session1.createQuery("from Province ").setCacheable(true).list();
HibernateUtil.close(session1);
}