MODULE 3 · TOPIC 4 · VISUAL JPA & HIBERNATE LAB

Queries with Entities using JPQL

JPQL queries the entity model: entity names, persistent attributes and association paths rather than raw table names. Hibernate translates the query into SQL for the configured dialect and converts the result to managed entities, scalar values or projections. This topic covers predicates, bound parameters, ordering, joins, grouping, pagination and bulk changes, including how they interact with the persistence context.

Browser-based JPA and Hibernate simulations. Change inputs and trace entity state, SQL, database rows and transactions. No real Java or database operations are executed.

1. JPQL SELECT — parameters, filtering and sorting

JPQL describes a selection using the Java entity and persistent fields. Hibernate converts it to SQL and binds parameters. Bound values stay separate from query structure, reducing injection risks. ORDER BY controls result order; use a unique tie-breaker for stable ordering.

Why this example? Select a marks threshold and sort order to inspect the generated SQL and matching rows.

Java / JPA code
SQL / simulation outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Why this step happens
See all steps in this scenario

    Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

    What this animation explains

    The same query structure works with different parameter values.

    Try and observe

    Choose 95 for an empty result, then change to 60 and reverse the sort.

    2. Entity and scalar projections

    A JPQL selection can return full entities, scalar values or constructor projections. Selecting only needed attributes can reduce data transferred and avoids managing unnecessary entity objects. The departmentCode field used in this example is an additional mapped String field.

    Why this example? Change result shape and department filter to compare types, columns and returned rows.

    Java / JPA code
    SQL / simulation outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected
    Why this step happens
    See all steps in this scenario

      Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

      What this animation explains

      The selection expression controls the type of result.

      Try and observe

      Select name-only and observe that marks and ID are absent from the result.

      3. JPQL association joins — inner versus left

      A join traverses a mapped association. INNER JOIN keeps matched combinations; LEFT JOIN also retains the left entity without a matching related row. Filtering the right side in WHERE can remove null-extended rows, so predicate placement matters. The lab selects parent and student identifiers, not a fetch join.

      Why this example? Choose join type and department filter for a dataset with one department containing no students.

      Java / JPA code
      SQL / simulation outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected
      Why this step happens
      See all steps in this scenario

        Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

        What this animation explains

        Join semantics determine whether empty parents disappear from the result.

        Try and observe

        Select MECH, then compare INNER JOIN and LEFT JOIN.

        4. Aggregates, GROUP BY and HAVING

        Aggregate functions summarize rows. GROUP BY partitions matching rows into groups, and HAVING filters those groups after aggregation. COUNT counts entities; AVG computes a numeric average. Unlike WHERE, HAVING may refer to aggregate values.

        Why this example? Select count or average and a minimum group size to inspect the grouped result.

        Java / JPA code
        SQL / simulation outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected
        Why this step happens
        See all steps in this scenario

          Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

          What this animation explains

          Groups can be removed even when their individual rows would satisfy WHERE.

          Try and observe

          Set group count 3; no group qualifies in this example.

          5. Pagination — offset, page size and ordering

          Large result sets are normally divided into pages. setFirstResult uses a zero-based offset, and setMaxResults limits the result count. Stable ordering is important to avoid ambiguous page boundaries; concurrent inserts and deletes can still shift offset pages.

          Why this example? Change page number and size; observe the computed offset and actual rows returned.

          Java / JPA code
          SQL / simulation outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected
          Why this step happens
          See all steps in this scenario

            Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

            What this animation explains

            Page number is not the same as the query offset.

            Try and observe

            Select page 3 with size 2 and notice an empty list.

            6. Bulk JPQL update — stale persistence context

            Bulk UPDATE and DELETE operate directly on rows and do not update existing managed entity instances. They require a transaction, and bulk update does not automatically implement normal optimistic version checks. Flush pending work before bulk operations, and clear or refresh afterward when needed.

            Why this example? Change marks increment and context strategy to see why the Java value can differ from the database.

            Java / JPA code
            SQL / simulation outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected
            Why this step happens
            See all steps in this scenario

              Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

              What this animation explains

              SQL success alone does not guarantee the managed object is fresh.

              Try and observe

              Keep context after +5 and see object marks 80 while database marks 85.

              API and configuration reference

              Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.

              API / settingWhy and when to use it
              em.createQuery(jpql, Student.class)Typed entity selection
              setParameter("min", value)Bind a named parameter
              getResultList()Return result list, possibly empty
              getSingleResult()Expect exactly one result; throws for zero or multiple results
              setFirstResult / setMaxResultsApply pagination
              executeUpdate()Execute bulk DML within transaction

              Worked practical examples

              Follow these procedures with the Jakarta Persistence 3.1 / Hibernate ORM 6.6 teaching project. Snippets require the indicated entities and an open EntityManager; SQL varies by dialect.

              1. Parameterized search with stable pagination

              Procedure

              1. Use the Student class and seed the four student rows.
              2. Open EntityManager and run a typed JPQL query.
              3. Bind the threshold and set the page size, then change firstResult for the next page.
              Code / configuration
              List<Student> list=em.createQuery(
               "SELECT s FROM Student s WHERE s.marks >= :min ORDER BY s.marks DESC, s.id", Student.class)
               .setParameter("min",60)
               .setFirstResult(0).setMaxResults(2)
               .getResultList();
              list.forEach(s->System.out.println(s.name+": "+s.marks));
              Expected result: With the stated dataset, 92 and 80 are the first two results.

              2. Bulk update and persistence-context synchronization

              Procedure

              1. Load student 101 into the context. Begin a transaction.
              2. Execute bulk JPQL; compare the managed instance before clearing.
              3. Clear or refresh after ensuring other pending edits have been flushed. Commit and reload.
              Code / configuration
              var tx=em.getTransaction();
              tx.begin();
              Student s=em.find(Student.class,101L);
              em.flush();
              int n=em.createQuery("UPDATE Student s SET s.marks=s.marks+5 WHERE s.id=:id")
               .setParameter("id",101L).executeUpdate();
              em.clear();
              tx.commit();
              System.out.println(em.find(Student.class,101L).marks);
              Expected result: The bulk update affects one row; the reload returns 85 for the stated seed data.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Why write Student rather than student in JPQL?

              Student is the entity name; SQL uses the physical table.

              2. Can setParameter substitute an ORDER BY column name?

              No. Validate allowed identifiers and construct that part deliberately.

              3. Why clear after bulk DML?

              Bulk DML updates database rows directly; the context may still contain stale objects.

              Hands-on practice and assessment

              Programming challenge

              Seed the Student entity with IDs 101–104 and marks 80, 65, 92 and 50. Run the select queries, inspect Hibernate SQL, then execute a bulk update in a transaction and compare a managed object with a freshly loaded one.

              Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.

              Quick assessment

              Key points and real Hibernate notes

              Query examples are illustrative and assume the mappings described in Introduction and Relationships. Parameters are for values, not identifiers or SQL fragments. For repeatable pagination, include a unique tie-breaker in ORDER BY.