一级缓存
首先你的Hibernate都是配好的这里就不一一赘述
首先看这样一段代码
Configuration cfg =new Configuration().configure();
SessionFactory sf=cfg.buildSessionFactory()
Session s=sf.openSession();
Emp emp=(Emp)s.get(Emp.class,19);
system.out.println(emp.ename);
s.close();
//
Emp emp1=(Emp)s.get(Emp.class,19);
system.out.println(emp1.ename);
s.close();
这样在执行两次sql语句
但是代码改成这样
Configuration cfg =new Configuration().configure();
SessionFactory sf=cfg.buildSessionFactory()
Session s=sf.openSession();
Emp emp=(Emp)s.get(Emp.class,19);
system.out.println(emp.ename);
//
Emp emp1=(Emp)s.get(Emp.class,19);
system.out.println(emp1.ename);
s.close();
这样将执行一次sql语句
二级缓存
配置二级缓存
1.导入架包有两个。
2.在hibernate.cfg.xml配置文件中添加
<property name="cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
org.hibernate.cache.EhCacheProvider
</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
3.在实体类的映射文件中加入 <cache usage="read-write"/>
4.在src下添加配置文件ehcache.xml文件
文件的内容为<diskStore path="c:\\cache"/>
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToLiveSeconds="120" overflowToDisk="true"/>
</ehcache>
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToLiveSeconds="120" overflowToDisk="true"/>
</ehcache>
这样就实现了二级缓存了二级缓存是存在SessionFactory中。
在Session关闭后还有缓存。缓存的方法就不在这里说了。