Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 31

    JPQL

    JPQL (Jakarta Persistence Query Language) queries entities and fields, not tables and columns.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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: @Param binding prevents injection.
    • @Modifying: required for UPDATE/DELETE JPQL.
    • projections: select new … for DTO constructor expressions.

    Step-by-step explanation

    1. Replace a long derived method with a readable @Query JPQL finder.
    2. Add join fetch o.items for the detail use case.
    3. Add a constructor-expression summary query.
    4. Write a status update with @Modifying + @Transactional.

    Informative example

    Orders JPQL: fetch join, projection, modifying update.

    java
    public interface OrderRepository extends JpaRepository<Order, Long> {
    @Query("""
    select o from Order o
    join fetch o.items
    where o.userId = :userId
    and o.status in :statuses
    order 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 userId in '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 @Modifying on 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.

    3 questions
    1BeginnerQuestionHow does JPQL differ from SQL?+

    Answer

    JPQL queries entities and fields; SQL queries tables and columns. JPQL is provider-translated to SQL per dialect.
    2IntermediateQuestionWhat does join fetch solve?+

    Answer

    It loads associations in the same query, avoiding N+1 lazy selects when the collection is accessed.
    3IntermediateQuestionWhy annotate bulk UPDATE with @Modifying?+

    Answer

    Spring Data treats queries as selects unless marked modifying; the annotation enables DML execution and optional clear/flush options.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.