Stage 6 - JPQL: Querying Entities Instead of Tables

JPQL queries the entity model, while SQL queries the database schema. It looks similar to SQL, but it operates on entity classes and entity fields, not directly on table names and column names. SQL says select * from users; JPQL says SELECT u FROM User u. Hibernate translates JPQL into SQL for the target database.

JPQL compared to SQL

JPQL syntax

The basic query selects from an entity:

@Query("SELECT u FROM User u")
List<User> findAllUsers();

User is the entity class name, and u is an alias. Conditions use entity field names:

@Query("SELECT u FROM User u WHERE u.email = :email")
Optional<User> findByEmail(@Param("email") String email);

JPQL supports WHERE, ORDER BY, GROUP BY, aggregate functions, and joins through entity relationships. A join follows object references, not raw foreign key columns:

@Query("SELECT o FROM Order o JOIN o.user u WHERE u.email = :email")
List<Order> findOrdersByUserEmail(@Param("email") String email);

Parameters

Named parameters use :name and are usually clearer than positional parameters. Positional parameters use ?1, ?2, and so on. Named parameters survive refactoring better because their meaning is visible in the query.

Query need Better JPQL style Why this explains the intent
Filter by one clear business value WHERE u.email = :email The parameter name documents that the value is an email, not just the first argument.
Filter by several values WHERE p.price BETWEEN :min AND :max Named parameters prevent confusion when two values have the same Java type.
Join through a relationship JOIN o.user u JPQL follows the entity relation instead of manually writing orders.user_id = users.id.
Return a list screen SELECT new ...ProductSummary(...) DTO projection loads only the fields that the response actually needs.

DTO projection

Sometimes an API needs only a few fields. Loading full entities can be wasteful, especially when relationships are involved. JPQL can create DTO projections:

@Query("""
    SELECT new com.example.UserSummary(u.id, u.email, u.name)
    FROM User u
    WHERE u.active = true
    ORDER BY u.name
""")
List<UserSummary> findActiveUserSummaries();

DTO projection is useful for read-only screens, list endpoints, and reporting. It reduces loaded data and avoids accidental lazy loading. The tradeoff is that the DTO constructor and query must match.

JPQL vs derived queries

Spring Data can create queries from method names, such as findByEmail or findByNameContainingIgnoreCase. This is excellent for simple conditions. JPQL is better when the query needs joins, grouping, custom sorting logic, projections, or a condition that would make the method name unreadable.

Glossary
ORM
Object-Relational Mapping, a technique that maps objects in code to relational database tables.
JDBC
The standard Java API for connecting to databases and executing SQL.
entity
A Java class mapped to a database table and managed by JPA as persistent data.
persistence context
The JPA runtime area that tracks managed entities and synchronizes them with the database.
repository
A data access abstraction that hides database operations behind methods such as save, find, and delete.
JpaRepository
A Spring Data JPA interface that provides common repository operations for an entity.
CRUD
The basic data operations create, read, update, and delete.
DTO
A Data Transfer Object used to carry data between layers or across an API boundary.
projection
A reduced or custom view of data selected from a larger entity or query result.
JPQL
A JPA query language that queries entities and fields instead of raw tables and columns.
derived query
A Spring Data query generated from a repository method name.
lazy loading
Loading related data only when it is first accessed.
eager loading
Loading related data immediately together with the main object.
cascade
A persistence rule that propagates an operation from one entity to related entities.
orphan removal
A JPA rule that deletes a child entity when it is removed from its parent relationship.
transactional
Describes code that runs inside a transaction boundary.
rollback
Cancelling a transaction so its database changes are not committed.
propagation
A transaction setting that defines how a method joins, creates, or rejects a transaction.