【发布时间】:2014-12-14 18:56:33
【问题描述】:
我需要一些关于 hibernate 如何缓存查询结果的指导。例如,如果我使用完全相同的参数一个接一个地发出两个 fetch 操作,是否会休眠两次连接到 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();
}
}
当我尝试上面的代码时,它会打印两次选择查询,这给我的印象是它连接到数据库并运行两次查询(我在日志文件中打印查询)。我使用了查询缓存。我的期望是它应该只对数据库运行一次查询并缓存结果。
【问题讨论】:
-
你告诉 Hibernate 它可以缓存查询,但你没有告诉它使用二级缓存,你还没有告诉它必须使用哪个缓存实现:docs.jboss.org/hibernate/core/4.3/manual/en-US/html_single/…
-
所以如果我不配置二级缓存它不会缓存结果。我认为一级缓存在这里应该仍然有效。
-
一级缓存从不缓存查询。即使是这样,它也与会话相关联,并且您正在使用两个不同的会话。