
1.一级缓存
hibernate的一级缓存是session级别的,所以如果session关闭后,缓存就没了,此时就会再次发sql去查数据库。
1 2 3 4 5 6 7 8 |
List<Student> stus = (List<Student>)session.createQuery( "from Student" )
.setFirstResult(0).setMaxResults(30).list();
Student stu = (Student)session.load(Student.class, 1);
|
2.二级缓存
hibernate二级缓存是由第三方提供以插件的形式存在,常用的缓存实现有Ehcache、oscache。
在hibernate.cfg.xml配置文件中配置我们二级缓存的一些属性
1 2 3 4 5 6 | <!-- 开启二级缓存 -->
<property name= "hibernate.cache.use_second_level_cache" > true </property>
<!-- 二级缓存的提供类 在hibernate4.0版本以后我们都是配置这个属性来指定二级缓存的提供类-->
<property name= "hibernate.cache.region.factory_class" >org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 二级缓存配置文件的位置 -->
<property name= "hibernate.cache.provider_configuration_file_resource_path" >ehcache.xml</property>
|
3.查询缓存
hibernate的查询缓存是主要是针对普通属性结果集的缓存, 而对于实体对象的结果集只缓存id。
在hibernate.cfg.xml配置文件中,开启查询缓存
1 2 | <!-- 是否开启查询缓存, true 开启查询缓存, false 关闭查询缓存 -->
<property name= "cache.use_query_cache" > true </property>
|
以上就是java中Hibernate的3种缓存形式,相信大家已经对它们有了初步的了解。如果还想具体分析到使用层面,可以在课后搜集相关的资料。
(本教程操作环境:windows7系统、java10版,DELL G3电脑。)