Enterprise Java Development@TOPIC@

Chapter 3. JPA Query Language

3.1. Simple Entity Query
3.2. Non-Entity Queries
3.3. Multi-select Query
3.3.1. Multi-select Query with Object[]
3.3.2. Multi-select Query with Tuple
3.3.3. Multi-select Query with Constructor
3.4. Path Expressions
3.4.1. Single Element Path Expressions
3.4.2. Collection Element Path Expressions
3.5. Eager Fetching through JOINs
3.5.1. Lazy Fetch Problem
3.5.2. Adding Eager Fetch during Query
3.6. Distinct Results
3.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