JPQL Named Query

Learn how to write a named query in Java Persistence Query Language (JPQL).

In the previous lesson, we implemented all CRUD operations except for the method corresponding to a SELECT * query. We will implement this method using a named query in Java Persistence Query Language (JPQL). A named query in JPA is a pre-defined query that is given a unique name and associated with an entity. Named queries allow us to encapsulate commonly used queries directly within our entity classes, promoting code reuse, readability, and maintainability.

A named query is defined on an entity, which in our case is the Player class. We will use the named query in a method called getAllPlayers() in the PlayerRepository.

@NamedQuery

To create a named query, we will use the @NamedQuery annotation on the Player class. This annotation requires two parameters: the name of the query and the query itself. When using JPA, we will write the query in JPQL instead of SQL. JPQLJPQL uses entities in place of tables. Since we want to return a list of Player objects, the query will be "SELECT p FROM Player p".

Get hands-on with 1400+ tech skills courses.