JPQL
JPQL (Jakarta Persistence Query Language) queries entities and fields, not tables and columns.
Introduction
JPQL (Jakarta Persistence Query Language) queries entities and fields, not tables and columns. It stays portable across MySQL and PostgreSQL for most Orders filters, and Spring Data exposes it through @Query.
Use JPQL when derived method names become unreadable, when you need join fetch to kill N+1, or when you project into a DTO constructor expression. Bulk updates and deletes require @Modifying and a transactional service method.
JPQL is not SQL. You write select o from Order o, not select * from orders. Association navigation uses entity fields: join fetch o.items. Parameters bind with :name or ordinal ?1 — never string concatenation.
Prefer JPQL for portable Orders reads; drop to native SQL only when you need Postgres-specific power.
Purpose of this lesson
Write Orders JPQL with Spring Data @Query, join fetch, projections, and safe modifying queries.
Understanding the topic
JPQL speaks the entity model.
- select from Entity: aliases map to classes, not tables.
- join fetch: initialize associations in one round trip.
- parameters:
@Parambinding prevents injection. - @Modifying: required for UPDATE/DELETE JPQL.
- projections:
select new …for DTO constructor expressions.
Step-by-step explanation
- Replace a long derived method with a readable
@QueryJPQL finder. - Add
join fetch o.itemsfor the detail use case. - Add a constructor-expression summary query.
- Write a status update with
@Modifying+@Transactional.
Informative example
Orders JPQL: fetch join, projection, modifying update.
public interface OrderRepository extends JpaRepository<Order, Long> {@Query("""select o from Order ojoin fetch o.itemswhere o.userId = :userIdand o.status in :statusesorder by o.createdAt desc""")List<Order> findFor(@Param("userId") Long userId,@Param("statuses") Collection<OrderStatus> statuses);@Query("""select new com.acme.orders.OrderSummary(o.id, o.status, o.totalCents)from Order o where o.userId = :uid""")List<OrderSummary> summariesFor(@Param("uid") Long uid);@Modifying(clearAutomatically = true)@Query("update Order o set o.status = :status where o.id = :id")int updateStatus(@Param("id") Long id, @Param("status") OrderStatus status);}
Output
findFor → 1 select with join (no N+1) updateStatus → 1 row updated
Real-world use
The TechLearningPRO 'my orders' screen needs headers plus line items without N+1. A single JPQL join fetch loads the aggregate for the authenticated user id; summaries use a constructor expression so list pages stay light.
Security implications
JPQL injection is still injection.
- Never build JPQL with string concatenation from request input.
- Always constrain by authenticated
userIdin 'my orders' queries. - Modifying queries must be authorized in the service before execution.
Best practices
- Bind every user-supplied value with
@Param. - Use join fetch only for associations you will read.
- Clear or refresh the persistence context after bulk modifying queries when needed.
Common mistakes
- Mixing table names into JPQL (
from orders) instead of entity names. - Forgetting
@Modifyingon UPDATE queries. - Join fetch + pagination in one query without understanding Hibernate limitations — separate count queries carefully.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionHow does JPQL differ from SQL?+
Answer
2IntermediateQuestionWhat does join fetch solve?+
Answer
3IntermediateQuestionWhy annotate bulk UPDATE with @Modifying?+
Answer
Hands-on exercise
Lab. Implement findFor with join fetch. Enable SQL logging and confirm one select. Then call updateStatus inside a transactional service and assert the row change.
Summary
JPQL covers portable Orders queries. Next: native SQL when PostgreSQL features outgrow JPQL.