hibernate缓存如何工作

时间:2014-12-14 18:56:34

标签: hibernate caching

我需要一些关于hibernate如何缓存查询结果的指导。例如,如果我使用完全相同的参数一个接一个地发出两个fetch操作,hibernate将连接到DB两次,对db运行查询两次并获取结果或者它将从第一次缓存结果?

public static void main( String[] args )
{

    App app = new App();


    try{
        factory = new AnnotationConfiguration().configure().
                addPackage("com.mantech.test").
                addAnnotatedClass(Address.class).
                buildSessionFactory();

        //addAddress();
        app.listAddress();
        System.out.println("---------------------------------");
        app.listAddress();

     }catch (Throwable ex) { 
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex); 
     }
}

   private void listAddress( ){
        Session session = factory.openSession();
        Transaction tx = null;
        try{
           tx = session.beginTransaction();
           List employees = session.createQuery("FROM Address a where a.city='Test'").setCacheable(true).list(); 
           System.out.println("Fetching Done");

           for (Iterator iterator = 
                             employees.iterator(); iterator.hasNext();){
               Address address = (Address) iterator.next(); 
              System.out.print("City Name: " + address.getCity()); 
              System.out.print("  Country Name: " + address.getCountry()); 
              System.out.println("  ID: " +address.getId()); 
           }
           tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
     }

当我尝试上面的代码时,它会打印两次选择查询,这让我觉得它连接到db并运行查询两次(我在日志文件中打印查询)。我用过查询缓存。我的期望是它应该只对DB运行一次查询并缓存结果。

1 个答案:

答案 0 :(得分:0)

您还没有使用查询缓存。对于查询缓存,您还需要启用二级缓存:

<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactoryy</property>