JPA: caching queries

前端 未结 6 1590
心在旅途
心在旅途 2021-02-07 08:13

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

6条回答
  •  天涯浪人
    2021-02-07 09:02

    Use statically defined named queries. They are more efficient because the JPA persistence provider can translate the JP QL string to SQL once at application startup time, as opposed to every time the query is executed, and are recommended in particular for queries that are executed frequently.

    A named query is defined using the @NamedQuery annotation that is typically used on the entity class of the result. In your case, on the Order entity:

    @Entity
    @NamedQueries({
        @NamedQuery(name="Order.findAll",
                    query="SELECT o FROM Order o"),
        @NamedQuery(name="Order.findByPrimaryKey",
                    query="SELECT o FROM Order o WHERE o.id = :id"),
        @NamedQuery(name="Order.findByCustomerId",
                    query="SELECT o FROM Order o WHERE o.customerId = :customerId")
    })
    public class Order implements Serializable {
        ...
    }
    

    It is also recommended to prefix named queries with the entity name (to have some kind of name space and avoid collisions).

    And then in the DAO:

    class OrderDao {
        EntityManager em;
    
        List getOrders(Long customerId) {
            return em.createNamedQuery("Order.findByCustomerId")
                     .setParameter("customerId", customerId);
                     .getResultList();
        }
    }
    

    PS: I reused the query you suggested as example but it's somehow weird to have the customerId on the Order, I would expect a Customer instead.

    References

    • JPA 1.0 Specification
      • Section 3.6.4 "Named Queries"

提交回复
热议问题