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
    See Also:
    Serialized Form