Hibernate JPA @NamedQuery Example

@NamedQuery

The @NamedQuery annotation extends the JPA @NamedQuery with Hibernate specific features, like:

  • flush mode for this particular query
  • if the query should be cached, and which cache region should be used
  • the selected entity CacheModeType strategy
  • the JDBC Statement fetch size
  • the JDBC Statement execution timeout
  • if the query is a CallableStatement, targeting a stored procedure or a database function
  • what SQL-level comment should be sent to the database
  • if the query is read-only, hence it does not store the resulted entities into the currently running Persistence Context

NamedQuery

Specifies a static, named query in the Java Persistence query language. Query names are scoped to the persistence unit. The NamedQuery annotation can be applied to an entity or mapped superclass.
The following is an example of the definition of a named query in the Java Persistence query language:

    @NamedQuery(
            name="findAllCustomersWithName",
            query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
    )

The following is an example of the use of a named query:

    @PersistenceContext
    public EntityManager em;
    ...
    customers = em.createNamedQuery("findAllCustomersWithName")
            .setParameter("custName", "Smith")
            .getResultList();

@NamedQueries({
    @NamedQuery(
        name = "get_phone_by_number",
        query = "select p " +
                "from Phone p " +
                "where p.number = :number",
        timeout = 1,
        readOnly = true
    )
})

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation