Enterprise Java Development@TOPIC@

Chapter 68. JPA Query Types

68.1. JPA Query Language (JPA-QL) Queries
68.2. Native SQL Queries
68.2.1. SqlResultSetMappings
68.3. Criteria API Queries
68.4. Strongly Typed Queries
68.4.1. Metamodel API
68.4.2. Query using JPA Metamodel
68.4.3. Canonical Metamodel
68.4.4. Generating Canonical Metamodel Classes
68.5. Summary

Three fundamental query types within JPA


  • "c" is part of root query

  • "c" represents rows from Customer entity table(s)

  • "c.firstName and c.lastName" are property paths off root term

  • ":firstName" is parameter placeholder

  • "Customer.class" type parameter allows for a type-safe return result


  • Placeholder is replaced by runtime parameter

  • Zero-or-more results are requested

  • Entities returned are managed



  • "c" represents rows in table

  • specific columns (or *) are return for each row

  • "?" marks a positional parameter -- non-portable to use named parameters in native SQL queries

  • TypedQuery<T>s not supported in native SQL queries because of a conflict with legacy JPA 1.0 API


  • Query execution similar to other query types

  • User-provided SQL executed

Note

Legacy JPA 1.0 Native SQL query syntax already used the signature of passing in a Class for createNativeQuery(). In this context, it was an entity class that contained JPA mappings for the query -- not the returned entity type. This prevented createNativeQuery() from being updated to return a typed result in JPA 2.0.







  • "CriteriaBuilder" used as starting point to build objects within the query tree

  • "CriteriaQuery<T>" used to hold the definition of query

  • "Root<T>" used to reference root level query terms

  • "CriteriaBuilder.from()" used to designate the entity that represents root query term

    • Result used to create path references for query body

  • "CriteriaBuilder.select()" officially lists the objects returned from query

  • "CriteriaBuilder.where()" builds a decision predicate of which entities to include

  • "CriteriaBuilder.equal()" builds an equals predicate for the where clause

  • "Root<T>.get()" returns the property referenced in path expression

  • "CriteriaBuilder.parameter()" builds a parameter placeholder within query. Useful with @Temporal date comparisons


  • Query execution identical to JPA-QL case



  • Access to properties within entities done through type-safe accessors


  • Results identical to previous approaches



  • Construct or generate a canonical metamodel class to provide type-safe, easy access to properties


  • Use canonical metamodel class to provide type-safe, easy access to properties ("Customer_.firstName")


  • Result is identical to previous approaches


  • More work to get here but clean, result

  • Type-safe - queries will not compile if entity changes