框架是spring+hibernate,配置了二级缓存;
第一种方法二级缓存生效:直接调用session。
第二种方法二级缓存无效:使用hibernateTemplate。
方法1:(调用两次以下方法,第二次没有打印sql)
s = sessionFactory.openSession();
tx = s.beginTransaction();
log.info("1 try to load application dsg.");
ApplicationDSG adsg = (ApplicationDSG) s.get(ApplicationDSG.class, appDSGId);
log.info(" --application dsg:" + adsg.toString());
方法2:使用hibernateTemplate
hibernateTemplate.setCacheQueries(true);
ApplicationDSG adsg1 = hibernateTemplate.get(ApplicationDSG.class, appDSGId);
Application a1 = adsg1.getApplication();
a1.getApplicationName();
ApplicationDSG adsg2 = hibernateTemplate.get(ApplicationDSG.class, appDSGId);
Application a2 = adsg2.getApplication();
a2.getApplicationName();
System.out.println(hibernateTemplate.getQueryCacheRegion());
Statistics statistics = sessionFactory.getStatistics();
System.out.println(statistics);
System.out.println("放入" + statistics.getSecondLevelCachePutCount());
System.out.println("命中" + statistics.getSecondLevelCacheHitCount());
System.out.println("错过" + statistics.getSecondLevelCacheMissCount());
hibernateTemplate 在xml中生成:
<!-- hibernate template -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
<property name="cacheQueries">
<value>${hibernate.template.cacheQueries}</value>
</property>
</bean>
方法1,2中的sessionFactory是一个。 问题不在这方面。
有没有知道这个是什么原因的?希望给与解答。
相关概念和定义
1、缓存的意义
把一些不常修改,但是又经常用的数据存放到内存中,这样能减少与数据库的交互,提升程序的性能
2、Hibernate中提供了两级缓存:
第一级别的缓存是Session级别的缓存(比如说在调用get方法的时候,如果已经查询过一次了,第二次就不会查了,而是直接返回session缓存中已经存在的那个对象给你,不过这个只对当前Session有效,一旦又开一个新的Se......
答案就在这里:Hibernate二级缓存问题
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。
通过看源码,Spring在创建new session时,有几个函数,注明二级缓存无效。估计是这个原因。但是why?还不知道
参见:SessionFactoryUtils
sessionFactory俗称session工厂,如果你的项目只使用了一个数据库,那么这个项目从头至尾都是这一个工厂,sessionFactory的实例化是通过反射来读取配置文件,并且只实例化一次