查询缓存不起作用

时间:2013-06-30 11:36:53

标签: java database hibernate orm ehcache

我正在为我的应用程序使用Hibernate 3.2.5。我正在尝试实施Query Cache,但它无效。

问题描述:

第一次触发数据库,​​获取数据并缓存数据。第二次,对于同一个查询,数据库被命中而不是从缓存中获取数据。第二次,我希望它从缓存中取出而不是再次访问数据库。

为了启用Query Cache,我在cfg.xml文件中输入了以下条目:

<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>

创建了文件:ehcache.xml并在hbm.xml文件中添加了以下条目:

<cache usage="read-only" />

以下是我尝试的代码:

SessionFactory sf = new Configuration().configure("trial.cfg.xml").buildSessionFactory();
    Session session = sf.openSession();

    List departments1 = session.createQuery("from Dept dept where dept.deptId = 1")
            .setCacheable(true)
            .setCacheRegion("departmentId")
            .list();        
    //Some business operations      
    session.flush();
    session.close();
    //Some business operations
    Session session1 = sf.openSession();        
    List departments2 = session1.createQuery("from Dept dept where dept.deptId = 1").list();        
    //In the above line again it is hitting the DB rather than taking it from the cache.

我相信我遗漏了一些东西,因为它没有从缓存中获取数据并因此命中数据库。请告诉我如何使Query Cache工作。

1 个答案:

答案 0 :(得分:1)

第二个查询不可缓存,因此不使用缓存。就这么简单。

请注意,如果这是您的真实代码,则应该简单地使用session.get(Dept.class, 1)来获取部门。