Enterprise Java Development@TOPIC@

Chapter 70. JPA Query Language

70.1. Simple Entity Query
70.2. Non-Entity Queries
70.3. Multi-select Query
70.3.1. Multi-select Query with Object[]
70.3.2. Multi-select Query with Tuple
70.3.3. Multi-select Query with Constructor
70.4. Path Expressions
70.4.1. Single Element Path Expressions
70.4.2. Collection Element Path Expressions
70.5. Eager Fetching through JOINs
70.5.1. Lazy Fetch Problem
70.5.2. Adding Eager Fetch during Query
70.6. Distinct Results
70.7. Summary


  • "select" defines root query objects -- all path references must start from this set

  • "from" defines source of root query terms

  • "as" (optional) identifies a variable assignment of entity in from clause

  • "object()" (optional) identifies what is returned for the path expressed in select clause (e.g., object(), count()) -- left over from EJBQL

  • no "where" clause indicates all entities are selected



  • Allows return of simple property

  • "c.lastName" is called a "path"

  • All paths based from root query terms

  • Single path selects return typed list of values


  • Query result is a List<String> because "c.lastName" is a String


  • Individual elements of select are matched up against class constructor


  • Constructed class may be simple POJO -- no need to be an entity

  • Instances are not managed

  • Suitable for use as Data Transfer Objects (DTOs)


  • Each row returned as instance of provided class


  • A normal JOIN (implicit or explicit) may honor the fetch=LAZY property setting of the relation

  • Can be exactly what is desired

  • Can also cause problems or extra work if not desired


  • Sales are lazily fetched when obtaining Store


  • Accessing the Sale properties causes a LazyInitializationException when persistence context no longer active or accessible

One Row per Parent is Returned for fetch=LAZY

Note that only a single row is required to be returned from the database for a fetch=LAZY relation. Although it requires more queries to the database, it eliminates duplicate parent information for each child row and can eliminate the follow-on query all together when not accessed.


  • Limits output to unique value combinations


  • Found three unique last names



  • Found two unique first names