hibernate缓存的工作原理

hibernate缓存的工作原理,hibernate,caching,Hibernate,Caching,我需要一些关于hibernate如何缓存查询结果的指导。例如,如果我使用完全相同的参数一个接一个地发出两个fetch操作,那么hibernate会连接到DB两次,对DB运行query两次并获取结果,还是会缓存第一次的结果 public static void main( String[] args ) { App app = new App(); try{ factory = new AnnotationConfiguration().configure()

我需要一些关于hibernate如何缓存查询结果的指导。例如,如果我使用完全相同的参数一个接一个地发出两个fetch操作,那么hibernate会连接到DB两次,对DB运行query两次并获取结果,还是会缓存第一次的结果

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(); 
        }
     }

当我尝试上面的代码时,它两次打印select查询,这给我的印象是它连接到db,并在日志文件中打印查询时两次运行查询。我使用了查询缓存。我的期望是,它应该只对数据库运行一次查询,并缓存结果

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

<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>

您告诉Hibernate它可以缓存查询,但您没有告诉它使用二级缓存,也没有告诉它必须使用哪个缓存实现:因此,如果我不配置二级缓存,它将不会缓存结果。我认为一级缓存应该仍然可以在这里工作。一级缓存从不缓存查询。即使有,它也与会话相关联,并且您正在使用两个不同的会话。@njain看一看