Class CriteriaDefinition<R>

Type Parameters:
R - the query result type
All Implemented Interfaces:
AbstractQuery<R>, CommonAbstractCriteria, CriteriaBuilder, CriteriaQuery<R>, Serializable, HibernateCriteriaBuilder, JpaCriteriaBase, JpaCriteriaNode, JpaCriteriaQuery<R>, JpaCteContainer, JpaQueryableCriteria<R>, JpaSelectCriteria<R>

@Incubating public abstract class CriteriaDefinition<R> extends HibernateCriteriaBuilderDelegate implements JpaCriteriaQuery<R>
A utility class that makes it easier to build criteria queries. From within an initializer block of a (usually anonymous) subclass, all operations of the CriteriaBuilder and CriteriaQuery may be called without the need for specifying the target object.

For example:

 sessionFactory.inTransaction(session -> {
     List<Book> books
             = new CriteriaDefinition<>(sessionFactory, Book.class) {{
                 var book = from(Book.class);
                 where(like(book.get(Book_.title), "%Hibernate%"));
                 orderBy(desc(book.get(Book_.publicationDate)), asc(book.get(Book_.isbn)));
                 book.fetch(Book_.authors);
             }}
             .createSelectionQuery(session)
             .setMaxResults(10)
             .getResultList();
     ...
 });
 

A CriteriaDefinition may even be used to modify a base HQL or criteria query:

 sessionFactory.inTransaction(session -> {
     List<Book> books
             = new CriteriaDefinition<>(sessionFactory, Book.class,
                     "from Book left join fetch authors where type = BOOK") {{
                 var book = (JpaRoot<Book>) getSelection();
                 where(getRestriction(), like(book.get(Book_.title), "%Hibernate%"));
                 orderBy(desc(book.get(Book_.publicationDate)), asc(book.get(Book_.isbn)));
             }}
             .createSelectionQuery(session)
             .getResultList();
     ...
 });
 
For queries which don't change between executions, the CriteriaDefinition may be safely built and cached at startup:
 // build and cache the query
 static final CriteriaQuery<Book> bookQuery =
         new CriteriaDefinition<>(sessionFactory, Book.class) {{
             var book = from(Book.class);
             where(like(book.get(Book_.title), "%Hibernate%"));
             orderBy(desc(book.get(Book_.publicationDate)), asc(book.get(Book_.isbn)));
             book.fetch(Book_.authors);
         }};

 ...

 // execute it in a session
 sessionFactory.inTransaction(session -> {
     List<Book> books =
             session.createQuery(bookQuery)
                     .setMaxResults(10)
                     .getResultList();
     ...
 });
 
Since:
6.3
Author:
Gavin King
See Also:
  • Constructor Details

  • Method Details

    • createSelectionQuery

      public SelectionQuery<R> createSelectionQuery(QueryProducer session)
    • createQuery

      public TypedQuery<R> createQuery(EntityManager entityManager)
    • restrict

      @Incubating public JpaCriteriaQuery<R> restrict(Predicate predicate)
    • select

      public JpaCriteriaQuery<R> select(Selection<? extends R> selection)
      Description copied from interface: CriteriaQuery
      Specify the item that is to be returned in the query result. Replaces the previously specified selection(s), if any.

      Note: Applications using the string-based API may need to specify the type of the select item when it results from a get or join operation and the query result type is specified.

           For example:
      
           CriteriaQuery<String> q = cb.createQuery(String.class);
           Root<Order> order = q.from(Order.class);
           q.select(order.get("shippingAddress").<String>get("state"));
       
           CriteriaQuery<Product> q2 = cb.createQuery(Product.class);
           q2.select(q2.from(Order.class)
                       .join("items")
                       .<Item,Product>join("product"));
       
       
      Specified by:
      select in interface CriteriaQuery<R>
      Specified by:
      select in interface JpaCriteriaQuery<R>
      Parameters:
      selection - selection specifying the item that is to be returned in the query result
      Returns:
      the modified query
    • multiselect

      public JpaCriteriaQuery<R> multiselect(Selection<?>... selections)
      Description copied from interface: CriteriaQuery
      Specify the selection items that are to be returned in the query result. Replaces the previously specified selection(s), if any. The type of the result of the query execution depends on the specification of the type of the criteria query object created as well as the arguments to the multiselect method.

      An argument to the multiselect method must not be a tuple- or array-valued compound selection item.

      The semantics of this method are as follows:

      • If the type of the criteria query is CriteriaQuery<Tuple> (i.e., a criteria query object created by either the createTupleQuery method or by passing a Tuple class argument to the createQuery method), a Tuple object corresponding to the arguments of the multiselect method, in the specified order, will be instantiated and returned for each row that results from the query execution.
      • If the type of the criteria query is CriteriaQuery<X> for some user-defined class X (i.e., a criteria query object created by passing a X class argument to the createQuery method), the arguments to the multiselect method will be passed to the X constructor and an instance of type X will be returned for each row.
      • If the type of the criteria query is CriteriaQuery<X[]> for some class X, an instance of type X[] will be returned for each row. The elements of the array will correspond to the arguments of the multiselect method, in the specified order.
      • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and only a single argument is passed to the multiselect method, an instance of type Object will be returned for each row.
      • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and more than one argument is passed to the multiselect method, an instance of type Object[] will be instantiated and returned for each row. The elements of the array will correspond to the arguments to the multiselect method, in the specified order.
      Specified by:
      multiselect in interface CriteriaQuery<R>
      Specified by:
      multiselect in interface JpaCriteriaQuery<R>
      Parameters:
      selections - selection items corresponding to the results to be returned by the query
      Returns:
      the modified query
    • multiselect

      public JpaCriteriaQuery<R> multiselect(List<Selection<?>> list)
      Description copied from interface: CriteriaQuery
      Specify the selection items that are to be returned in the query result. Replaces the previously specified selection(s), if any.

      The type of the result of the query execution depends on the specification of the type of the criteria query object created as well as the argument to the multiselect method. An element of the list passed to the multiselect method must not be a tuple- or array-valued compound selection item.

      The semantics of this method are as follows:

      • If the type of the criteria query is CriteriaQuery<Tuple> (i.e., a criteria query object created by either the createTupleQuery method or by passing a Tuple class argument to the createQuery method), a Tuple object corresponding to the elements of the list passed to the multiselect method, in the specified order, will be instantiated and returned for each row that results from the query execution.
      • If the type of the criteria query is CriteriaQuery<X> for some user-defined class X (i.e., a criteria query object created by passing a X class argument to the createQuery method), the elements of the list passed to the multiselect method will be passed to the X constructor and an instance of type X will be returned for each row.
      • If the type of the criteria query is CriteriaQuery<X[]> for some class X, an instance of type X[] will be returned for each row. The elements of the array will correspond to the elements of the list passed to the multiselect method, in the specified order.
      • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and the list passed to the multiselect method contains only a single element, an instance of type Object will be returned for each row.
      • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and the list passed to the multiselect method contains more than one element, an instance of type Object[] will be instantiated and returned for each row. The elements of the array will correspond to the elements of the list passed to the multiselect method, in the specified order.
      Specified by:
      multiselect in interface CriteriaQuery<R>
      Specified by:
      multiselect in interface JpaCriteriaQuery<R>
      Parameters:
      list - list of selection items corresponding to the results to be returned by the query
      Returns:
      the modified query
    • where

      public JpaCriteriaQuery<R> where(Expression<Boolean> restriction)
      Description copied from interface: CriteriaQuery
      Modify the query to restrict the query result according to the specified boolean expression. Replaces the previously added restriction(s), if any. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      where in interface AbstractQuery<R>
      Specified by:
      where in interface CriteriaQuery<R>
      Specified by:
      where in interface JpaCriteriaQuery<R>
      Specified by:
      where in interface JpaSelectCriteria<R>
      Parameters:
      restriction - a simple or compound boolean expression
      Returns:
      the modified query
    • where

      public JpaCriteriaQuery<R> where(Predicate... restrictions)
      Description copied from interface: CriteriaQuery
      Modify the query to restrict the query result according to the conjunction of the specified restriction predicates. Replaces the previously added restriction(s), if any. If no restrictions are specified, any previously added restrictions are simply removed. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      where in interface AbstractQuery<R>
      Specified by:
      where in interface CriteriaQuery<R>
      Specified by:
      where in interface JpaCriteriaQuery<R>
      Specified by:
      where in interface JpaSelectCriteria<R>
      Parameters:
      restrictions - zero or more restriction predicates
      Returns:
      the modified query
    • groupBy

      public JpaCriteriaQuery<R> groupBy(Expression... grouping)
      Description copied from interface: CriteriaQuery
      Specify the expressions that are used to form groups over the query results. Replaces the previous specified grouping expressions, if any. If no grouping expressions are specified, any previously added grouping expressions are simply removed. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      groupBy in interface AbstractQuery<R>
      Specified by:
      groupBy in interface CriteriaQuery<R>
      Specified by:
      groupBy in interface JpaCriteriaQuery<R>
      Specified by:
      groupBy in interface JpaSelectCriteria<R>
      Parameters:
      grouping - zero or more grouping expressions
      Returns:
      the modified query
    • groupBy

      public JpaCriteriaQuery<R> groupBy(List<Expression<?>> grouping)
      Description copied from interface: CriteriaQuery
      Specify the expressions that are used to form groups over the query results. Replaces the previous specified grouping expressions, if any. If no grouping expressions are specified, any previously added grouping expressions are simply removed. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      groupBy in interface AbstractQuery<R>
      Specified by:
      groupBy in interface CriteriaQuery<R>
      Specified by:
      groupBy in interface JpaCriteriaQuery<R>
      Specified by:
      groupBy in interface JpaSelectCriteria<R>
      Parameters:
      grouping - list of zero or more grouping expressions
      Returns:
      the modified query
    • having

      public JpaCriteriaQuery<R> having(Expression<Boolean> restriction)
      Description copied from interface: CriteriaQuery
      Specify a restriction over the groups of the query. Replaces the previous having restriction(s), if any. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      having in interface AbstractQuery<R>
      Specified by:
      having in interface CriteriaQuery<R>
      Specified by:
      having in interface JpaCriteriaQuery<R>
      Specified by:
      having in interface JpaSelectCriteria<R>
      Parameters:
      restriction - a simple or compound boolean expression
      Returns:
      the modified query
    • having

      public JpaCriteriaQuery<R> having(Predicate... restrictions)
      Description copied from interface: CriteriaQuery
      Specify restrictions over the groups of the query according the conjunction of the specified restriction predicates. Replaces the previously added having restriction(s), if any. If no restrictions are specified, any previously added restrictions are simply removed. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      having in interface AbstractQuery<R>
      Specified by:
      having in interface CriteriaQuery<R>
      Specified by:
      having in interface JpaCriteriaQuery<R>
      Specified by:
      having in interface JpaSelectCriteria<R>
      Parameters:
      restrictions - zero or more restriction predicates
      Returns:
      the modified query
    • orderBy

      public JpaCriteriaQuery<R> orderBy(Order... o)
      Description copied from interface: CriteriaQuery
      Specify the ordering expressions that are used to order the query results. Replaces the previous ordering expressions, if any. If no ordering expressions are specified, the previous ordering, if any, is simply removed, and results will be returned in no particular order. The left-to-right sequence of the ordering expressions determines the precedence, whereby the leftmost has highest precedence.
      Specified by:
      orderBy in interface CriteriaQuery<R>
      Specified by:
      orderBy in interface JpaCriteriaQuery<R>
      Parameters:
      o - zero or more ordering expressions
      Returns:
      the modified query
    • orderBy

      public JpaCriteriaQuery<R> orderBy(List<Order> o)
      Description copied from interface: CriteriaQuery
      Specify the ordering expressions that are used to order the query results. Replaces the previous ordering expressions, if any. If no ordering expressions are specified, the previous ordering, if any, is simply removed, and results will be returned in no particular order. The order of the ordering expressions in the list determines the precedence, whereby the first element in the list has highest precedence.
      Specified by:
      orderBy in interface CriteriaQuery<R>
      Specified by:
      orderBy in interface JpaCriteriaQuery<R>
      Parameters:
      o - list of zero or more ordering expressions
      Returns:
      the modified query
    • distinct

      public JpaCriteriaQuery<R> distinct(boolean distinct)
      Description copied from interface: CriteriaQuery
      Specify whether duplicate query results will be eliminated. A true value will cause duplicates to be eliminated. A false value will cause duplicates to be retained. If distinct has not been specified, duplicate results must be retained. This method only overrides the return type of the corresponding AbstractQuery method.
      Specified by:
      distinct in interface AbstractQuery<R>
      Specified by:
      distinct in interface CriteriaQuery<R>
      Specified by:
      distinct in interface JpaCriteriaQuery<R>
      Specified by:
      distinct in interface JpaSelectCriteria<R>
      Parameters:
      distinct - boolean value specifying whether duplicate results must be eliminated from the query result or whether they must be retained
      Returns:
      the modified query.
    • getOrderList

      public List<Order> getOrderList()
      Description copied from interface: CriteriaQuery
      Return the ordering expressions in order of precedence. Returns empty list if no ordering expressions have been specified. Modifications to the list do not affect the query.
      Specified by:
      getOrderList in interface CriteriaQuery<R>
      Specified by:
      getOrderList in interface JpaCriteriaQuery<R>
      Returns:
      the list of ordering expressions
    • getParameters

      public Set<ParameterExpression<?>> getParameters()
      Description copied from interface: JpaCriteriaQuery
      Return the parameters of the query. Returns empty set if there are no parameters. Modifications to the set do not affect the query.
      Specified by:
      getParameters in interface CriteriaQuery<R>
      Specified by:
      getParameters in interface JpaCriteriaQuery<R>
      Returns:
      the query parameters
    • from

      public <X> JpaRoot<X> from(Class<X> entityClass)
      Description copied from interface: AbstractQuery
      Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.
      Specified by:
      from in interface AbstractQuery<R>
      Specified by:
      from in interface JpaCriteriaQuery<R>
      Specified by:
      from in interface JpaSelectCriteria<R>
      Parameters:
      entityClass - the entity class
      Returns:
      query root corresponding to the given entity
    • from

      public <X> JpaRoot<X> from(EntityType<X> entity)
      Description copied from interface: AbstractQuery
      Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.
      Specified by:
      from in interface AbstractQuery<R>
      Specified by:
      from in interface JpaCriteriaQuery<R>
      Specified by:
      from in interface JpaSelectCriteria<R>
      Parameters:
      entity - metamodel entity representing the entity of type X
      Returns:
      query root corresponding to the given entity
    • subquery

      public <U> JpaSubQuery<U> subquery(Class<U> type)
      Description copied from interface: CommonAbstractCriteria
      Create a subquery of the query.
      Specified by:
      subquery in interface CommonAbstractCriteria
      Specified by:
      subquery in interface JpaCriteriaBase
      Parameters:
      type - the subquery result type
      Returns:
      subquery
    • getRoots

      public Set<Root<?>> getRoots()
      Description copied from interface: AbstractQuery
      Return the query roots. These are the roots that have been defined for the CriteriaQuery or Subquery itself, including any subquery roots defined as a result of correlation. Returns empty set if no roots have been defined. Modifications to the set do not affect the query.
      Specified by:
      getRoots in interface AbstractQuery<R>
      Returns:
      the set of query roots
    • getSelection

      public JpaSelection<R> getSelection()
      Description copied from interface: AbstractQuery
      Return the selection of the query, or null if no selection has been set.
      Specified by:
      getSelection in interface AbstractQuery<R>
      Specified by:
      getSelection in interface JpaSelectCriteria<R>
      Returns:
      selection item
    • getGroupList

      public List<Expression<?>> getGroupList()
      Description copied from interface: AbstractQuery
      Return a list of the grouping expressions. Returns empty list if no grouping expressions have been specified. Modifications to the list do not affect the query.
      Specified by:
      getGroupList in interface AbstractQuery<R>
      Returns:
      the list of grouping expressions
    • getGroupRestriction

      public JpaPredicate getGroupRestriction()
      Description copied from interface: AbstractQuery
      Return the predicate that corresponds to the restriction(s) over the grouping items, or null if no restrictions have been specified.
      Specified by:
      getGroupRestriction in interface AbstractQuery<R>
      Specified by:
      getGroupRestriction in interface JpaSelectCriteria<R>
      Returns:
      having clause predicate
    • isDistinct

      public boolean isDistinct()
      Description copied from interface: AbstractQuery
      Return whether duplicate query results must be eliminated or retained.
      Specified by:
      isDistinct in interface AbstractQuery<R>
      Returns:
      boolean indicating whether duplicate query results must be eliminated
    • getResultType

      public Class<R> getResultType()
      Description copied from interface: AbstractQuery
      Return the result type of the query or subquery. If a result type was specified as an argument to the createQuery or subquery method, that type will be returned. If the query was created using the createTupleQuery method, the result type is Tuple. Otherwise, the result type is Object.
      Specified by:
      getResultType in interface AbstractQuery<R>
      Returns:
      result type
    • getRestriction

      public JpaPredicate getRestriction()
      Description copied from interface: CommonAbstractCriteria
      Return the predicate that corresponds to the where clause restriction(s), or null if no restrictions have been specified.
      Specified by:
      getRestriction in interface CommonAbstractCriteria
      Specified by:
      getRestriction in interface JpaCriteriaBase
      Specified by:
      getRestriction in interface JpaSelectCriteria<R>
      Returns:
      where clause predicate
    • getOffset

      public JpaExpression<Number> getOffset()
      Specified by:
      getOffset in interface JpaCriteriaQuery<R>
    • offset

      public JpaCriteriaQuery<R> offset(JpaExpression<? extends Number> offset)
      Specified by:
      offset in interface JpaCriteriaQuery<R>
    • offset

      public JpaCriteriaQuery<R> offset(Number offset)
      Specified by:
      offset in interface JpaCriteriaQuery<R>
    • getFetch

      public JpaExpression<Number> getFetch()
      Specified by:
      getFetch in interface JpaCriteriaQuery<R>
    • fetch

      public JpaCriteriaQuery<R> fetch(JpaExpression<? extends Number> fetch)
      Specified by:
      fetch in interface JpaCriteriaQuery<R>
    • fetch

      public JpaCriteriaQuery<R> fetch(JpaExpression<? extends Number> fetch, FetchClauseType fetchClauseType)
      Specified by:
      fetch in interface JpaCriteriaQuery<R>
    • fetch

      public JpaCriteriaQuery<R> fetch(Number fetch)
      Specified by:
      fetch in interface JpaCriteriaQuery<R>
    • fetch

      public JpaCriteriaQuery<R> fetch(Number fetch, FetchClauseType fetchClauseType)
      Specified by:
      fetch in interface JpaCriteriaQuery<R>
    • getFetchClauseType

      public FetchClauseType getFetchClauseType()
      Specified by:
      getFetchClauseType in interface JpaCriteriaQuery<R>
    • getRootList

      public List<Root<?>> getRootList()
      Description copied from interface: JpaCriteriaQuery
      Return the roots as a list.
      Specified by:
      getRootList in interface JpaCriteriaQuery<R>
    • getCteCriterias

      public Collection<? extends JpaCteCriteria<?>> getCteCriterias()
      Description copied from interface: JpaCteContainer
      Returns the CTEs that are registered on this container.
      Specified by:
      getCteCriterias in interface JpaCteContainer
    • getCteCriteria

      public <T> JpaCteCriteria<T> getCteCriteria(String cteName)
      Description copied from interface: JpaCteContainer
      Returns a CTE that is registered by the given name on this container, or any of its parents.
      Specified by:
      getCteCriteria in interface JpaCteContainer
    • with

      public <T> JpaCteCriteria<T> with(AbstractQuery<T> criteria)
      Description copied from interface: JpaCteContainer
      Registers the given CriteriaQuery and returns a JpaCteCriteria, which can be used for querying.
      Specified by:
      with in interface JpaCteContainer
      See Also:
    • withRecursiveUnionAll

      public <T> JpaCteCriteria<T> withRecursiveUnionAll(AbstractQuery<T> baseCriteria, Function<JpaCteCriteria<T>,AbstractQuery<T>> recursiveCriteriaProducer)
      Description copied from interface: JpaCteContainer
      Allows to register a recursive CTE. The base CriteriaQuery serves for the structure of the JpaCteCriteria, which is made available in the recursive criteria producer function, so that the recursive CriteriaQuery is able to refer to the CTE again.
      Specified by:
      withRecursiveUnionAll in interface JpaCteContainer
      See Also:
    • withRecursiveUnionDistinct

      public <T> JpaCteCriteria<T> withRecursiveUnionDistinct(AbstractQuery<T> baseCriteria, Function<JpaCteCriteria<T>,AbstractQuery<T>> recursiveCriteriaProducer)
      Description copied from interface: JpaCteContainer
      Allows to register a recursive CTE. The base CriteriaQuery serves for the structure of the JpaCteCriteria, which is made available in the recursive criteria producer function, so that the recursive CriteriaQuery is able to refer to the CTE again.
      Specified by:
      withRecursiveUnionDistinct in interface JpaCteContainer
      See Also:
    • with

      public <T> JpaCteCriteria<T> with(String name, AbstractQuery<T> criteria)
      Description copied from interface: JpaCteContainer
      Like JpaCteContainer.with(AbstractQuery) but assigns an explicit CTE name.
      Specified by:
      with in interface JpaCteContainer
    • withRecursiveUnionAll

      public <T> JpaCteCriteria<T> withRecursiveUnionAll(String name, AbstractQuery<T> baseCriteria, Function<JpaCteCriteria<T>,AbstractQuery<T>> recursiveCriteriaProducer)
      Description copied from interface: JpaCteContainer
      Specified by:
      withRecursiveUnionAll in interface JpaCteContainer
    • withRecursiveUnionDistinct

      public <T> JpaCteCriteria<T> withRecursiveUnionDistinct(String name, AbstractQuery<T> baseCriteria, Function<JpaCteCriteria<T>,AbstractQuery<T>> recursiveCriteriaProducer)
      Description copied from interface: JpaCteContainer
      Specified by:
      withRecursiveUnionDistinct in interface JpaCteContainer
    • getQuerySpec

      public JpaQueryStructure<R> getQuerySpec()
      Description copied from interface: JpaSelectCriteria
      The query structure. See JpaQueryStructure for details
      Specified by:
      getQuerySpec in interface JpaSelectCriteria<R>
    • getQueryPart

      public JpaQueryPart<R> getQueryPart()
      Description copied from interface: JpaSelectCriteria
      The query structure. See JpaQueryStructure for details
      Specified by:
      getQueryPart in interface JpaSelectCriteria<R>
    • from

      public <X> JpaDerivedRoot<X> from(Subquery<X> subquery)
      Description copied from interface: JpaSelectCriteria
      Create and add a query root corresponding to the given subquery, forming a cartesian product with any existing roots.
      Specified by:
      from in interface JpaSelectCriteria<R>
      Parameters:
      subquery - the subquery
      Returns:
      query root corresponding to the given subquery
    • from

      public <X> JpaRoot<X> from(JpaCteCriteria<X> cte)
      Description copied from interface: JpaSelectCriteria
      Create and add a query root corresponding to the given cte, forming a cartesian product with any existing roots.
      Specified by:
      from in interface JpaSelectCriteria<R>
      Parameters:
      cte - the cte criteria
      Returns:
      query root corresponding to the given cte
    • createCountQuery

      public JpaCriteriaQuery<Long> createCountQuery()
      Description copied from interface: JpaCriteriaQuery
      A query that returns the number of results of this query.
      Specified by:
      createCountQuery in interface JpaCriteriaQuery<R>
      See Also: