Close

Named Queries

[Updated: May 27, 2018, Created: May 27, 2018]

Named queries are reusable static queries that we create and associate with an entity.
At runtime, we can use the EntityManager to acquire, configure, and execute a named query.

Named queries can be created using annotation javax.persistence.NamedQuery which specifies the name of the query and query (in JPQL) itself.

During runtime we can use EntityManager#createNamedQuery() method to access them.

Example

Entities

@Entity
@NamedQuery(name = Employee.SALARY_RANGE_QUERY,
      query = "SELECT e FROM Employee e WHERE e.salary BETWEEN :min AND :max order by e.salary")
@NamedQuery(name = Employee.SALARY_LESS_THAN_AVERAGE_QUERY,
      query = "SELECT e FROM Employee e where  e.salary < (SELECT AVG(e2.salary) FROM Employee e2)")
public class Employee {
  public static final String SALARY_RANGE_QUERY = "salaryRangeQuery";
  public static final String SALARY_LESS_THAN_AVERAGE_QUERY = "salaryLessThanAverageQuery";
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private Timestamp joinDate;
  private long salary;
    .............
}

As @NameQuery is a repeatable annotation, we can use multiple of them on entity classes.

Executing named queries

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEmployees();
          findEmployeeBySalaryRange();
          findEmployeeWithLessThanAverageSalary();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void findEmployeeBySalaryRange() {
      System.out.println("-- Employee by salary range --");
      EntityManager em = entityManagerFactory.createEntityManager();
      Query query = em.createNamedQuery(Employee.SALARY_RANGE_QUERY);
      query.setParameter("min", 2000L);
      query.setParameter("max", 4000L);
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }

  private static void findEmployeeWithLessThanAverageSalary() {
      System.out.println("-- Employee with salary less than average --");
      EntityManager em = entityManagerFactory.createEntityManager();
      Query query = em.createNamedQuery(Employee.SALARY_LESS_THAN_AVERAGE_QUERY);
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", 3000, LocalDate.of(1999, 11, 15));
      Employee employee2 = Employee.create("Rose", 4000, LocalDate.of(2011, 5, 1));
      Employee employee3 = Employee.create("Denise", 1500, LocalDate.of(2006, 1, 10));
      Employee employee4 = Employee.create("Mike", 2000, LocalDate.of(2015, 8, 20));
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee1);
      em.persist(employee2);
      em.persist(employee3);
      em.persist(employee4);
      em.getTransaction().commit();
      em.close();
  }

  private static Timestamp localToTimeStamp(LocalDate date) {
      return Timestamp.from(date.atStartOfDay().toInstant(ZoneOffset.UTC));
  }
}
-- Employee by salary range --
Employee{id=4, name='Mike', joinDate=2015-08-19 19:00:00.0, salary=2000}
Employee{id=1, name='Diana', joinDate=1999-11-14 18:00:00.0, salary=3000}
Employee{id=2, name='Rose', joinDate=2011-04-30 19:00:00.0, salary=4000}
-- Employee with salary less than average --
Employee{id=3, name='Denise', joinDate=2006-01-09 18:00:00.0, salary=1500}
Employee{id=4, name='Mike', joinDate=2015-08-19 19:00:00.0, salary=2000}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.197: H2 Database Engine.
  • hibernate-core 5.3.1.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • JDK 1.8
  • Maven 3.3.9

@NamedQuery Example Select All Download
  • jpa-named-queries-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
          • resources
            • META-INF

    See Also