JPA:缓存查询 [英] JPA: caching queries

查看:384
本文介绍了JPA:缓存查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JPA在基于Java EE的Web应用程序中加载和保存实体。 Hibernate用作JPA的实现,但我没有使用Hibernate特有的功能,只能用于纯JPA。

I'm using JPA to load and persist entities in my Java EE-based web application. Hibernate is used as an implementation of JPA, but I don't use Hibernate-specific features and only work with pure JPA.

以下是一些DAO类,请注意 getOrders 方法:

Here is some DAO class, notice getOrders method:

class OrderDao {
  EntityManager em;

  List getOrders(Long customerId) {
    Query q = em.createQuery(
      "SELECT o FROM Order o WHERE o.customerId = :customerId");
    q.setParameter("customerId", customerId);
    return q.getResultList();
  }
}

方法非常简单,但它有一个很大的缺点。每次调用该方法时,都会在JPA实现中执行以下操作:

Method is pretty simple but it has a big drawback. Each time the method is called following actions are performed somewhere within JPA implementation:


  1. JPQL表达式被解析并编译为SQL。
  2. 创建并初始化Statement或PreparedStatement实例。
  3. 语句实例充满参数并执行。
  1. JPQL expression is parsed and compiled to SQL.
  2. Either Statement or PreparedStatement instance is created and initialized.
  3. Statement instance is filled with parameters and executed.

我相信上面的步骤1和2应该在每个应用程序生命周期中执行一次。但如何做到这一点?换句话说,我需要将这些Query实例缓存起来。

I believe that steps 1 and 2 of above should be implemented once per application lifetime. But how to make it? In other words, I need that Query instances to be cached.

当然,我可以在我这边实现这样的缓存。但是等等,我正在使用现代强大的ORM!难道他们不是已经为我做了这件事吗?

Of course I can implement such a cache on my side. But wait, I am using modern powerful ORM's! Didn't they already made this for me?

请注意,我没有提到像缓存查询结果的Hibernate查询缓存。在这里,我希望更快地执行我的查询。

Notice that I'm not mentioning something like Hibernate query cache which caches result of queries. Here I'd like to execute my queries a bit more quickly.

推荐答案

这是Hibernate中的查询计划缓存。因此,每次调用DAO时都不会分析HQL(因此#1在应用程序生命周期中确实只会出现一次)。它是 QueryPlanCache 。它没有大量记录,因为它正常工作。但您可以在此处找到更多信息。

The is a query plan cache in Hibernate. So the HQL is not parsed every time the DAO is called (so #1 really occurs only once in your application life-time). It's QueryPlanCache. It's not heavily documented, as it "just works". But you can find more info here.

这篇关于JPA:缓存查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆