Class TQRootBean<T,​R>

  • Type Parameters:
    T - the entity bean type (normal entity bean type e.g. Customer)
    R - the specific root query bean type (e.g. QCustomer)

    @NonNullApi
    public abstract class TQRootBean<T,​R>
    extends Object
    Base root query bean providing common features for all root query beans.

    For each entity bean querybean-generator generates a query bean that extends TQRootBean.

    Example - usage of QCustomer

    
    
      Date fiveDaysAgo = ...
    
      List<Customer> customers =
          new QCustomer()
            .name.ilike("rob")
            .status.equalTo(Customer.Status.GOOD)
            .registered.after(fiveDaysAgo)
            .contacts.email.endsWith("@foo.com")
            .orderBy()
              .name.asc()
              .registered.desc()
            .findList();
    
     

    Resulting SQL where

    
    
       where lower(t0.name) like ?  and t0.status = ?  and t0.registered > ?  and u1.email like ?
       order by t0.name, t0.registered desc;
    
       --bind(rob,GOOD,Mon Jul 27 12:05:37 NZST 2015,%@foo.com)
    
     
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
        TQRootBean​(boolean aliasDummy)
      Construct for using as an 'Alias' to use the properties as known string values for select() and fetch().
        TQRootBean​(io.ebean.Query<T> query)
      Construct using a query.
        TQRootBean​(Class<T> beanType)
      Construct using the type of bean to query on and the default database.
        TQRootBean​(Class<T> beanType, io.ebean.Database database)
      Construct using the type of bean to query on and a given database.
      protected TQRootBean​(Class<T> beanType, io.ebean.Database database, io.ebean.Transaction transaction)
      Construct with a database and transaction.
      protected TQRootBean​(Class<T> beanType, io.ebean.Transaction transaction)
      Construct with a transaction.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected io.ebean.ExpressionList<T> _peekText()  
      R alias​(String alias)
      Set root table alias.
      R and()
      Begin a list of expressions added by 'AND'.
      R apply​(io.ebean.text.PathProperties pathProperties)
      Apply the path properties replacing the select and fetch clauses.
      R asDraft()
      Execute the query against the draft set of tables.
      <D> io.ebean.DtoQuery<D> asDto​(Class<D> dtoClass)
      Convert the query to a DTO bean query.
      R asOf​(Timestamp asOf)
      Perform an 'As of' query using history tables to return the object graph as of a time in the past.
      io.ebean.UpdateQuery<T> asUpdate()
      Return this query as an UpdateQuery.
      io.ebean.FetchGroup<T> buildFetchGroup()
      Return the fetch group.
      int delete()
      Execute as a delete query deleting the 'root level' beans that match the predicates in the query.
      R endAnd()
      End AND junction - synonym for endJunction().
      R endJunction()
      End a list of expressions added by 'OR'.
      R endNot()
      End NOT junction - synonym for endJunction().
      R endOr()
      End OR junction - synonym for endJunction().
      boolean exists()
      Execute the query returning true if a row is found.
      R fetch​(String path)
      Specify a path to load including all its properties.
      R fetch​(String path, io.ebean.FetchConfig fetchConfig)
      Additionally specify a FetchConfig to specify a "query join" and or define the lazy loading query.
      R fetch​(String path, String properties)
      Specify a path to fetch with its specific properties to include (aka partial object).
      R fetch​(String path, String properties, io.ebean.FetchConfig fetchConfig)
      Additionally specify a FetchConfig to use a separate query or lazy loading to load this path.
      R fetchCache​(String path)
      Specify a path to load from L2 cache including all its properties.
      R fetchCache​(String path, String properties)
      Specify a path and properties to load from L2 cache.
      R fetchQuery​(String path)
      Specify a path to load including all its properties using a "query join".
      R fetchQuery​(String path, String properties)
      Specify a path and properties to load using a "query join".
      int findCount()
      Return the count of entities this query should return.
      void findEach​(int batch, Consumer<List<T>> consumer)
      Execute findEach streaming query batching the results for consuming.
      void findEach​(Consumer<T> consumer)
      Execute the query processing the beans one at a time.
      void findEachWhile​(Predicate<T> consumer)
      Execute the query using callbacks to a visitor to process the resulting beans one at a time.
      io.ebean.FutureRowCount<T> findFutureCount()
      Execute find row count query in a background thread.
      io.ebean.FutureIds<T> findFutureIds()
      Execute find Id's query in a background thread.
      io.ebean.FutureList<T> findFutureList()
      Execute find list query in a background thread.
      <A> List<A> findIds()
      Execute the query returning the list of Id's.
      io.ebean.QueryIterator<T> findIterate()
      Execute the query iterating over the results.
      List<T> findList()
      Execute the query returning the list of objects.
      <K> Map<K,​T> findMap()
      Execute the query returning a map of the objects.
      T findOne()
      Execute the query returning either a single bean or null (if no matching bean is found).
      Optional<T> findOneOrEmpty()
      Execute the query returning an optional bean.
      io.ebean.PagedList<T> findPagedList()
      Return a PagedList for this query using firstRow and maxRows.
      Set<T> findSet()
      Execute the query returning the set of objects.
      <A> A findSingleAttribute()
      Execute the query returning a single value for a single property.
      <A> List<A> findSingleAttributeList()
      Execute the query returning a list of values for a single property.
      Stream<T> findStream()
      Execute the query returning the result as a Stream.
      List<io.ebean.Version<T>> findVersions()
      Return versions of a @History entity bean.
      List<io.ebean.Version<T>> findVersionsBetween​(Timestamp start, Timestamp end)
      Return versions of a @History entity bean between a start and end timestamp.
      R forUpdate()
      Execute using "for update" clause which results in the DB locking the record.
      R forUpdateNoWait()
      Execute using "for update" clause with "no wait" option.
      R forUpdateSkipLocked()
      Execute using "for update" clause with "skip locked" option.
      Class<T> getBeanType()
      Return the type of beans being queried.
      io.ebean.ExpressionList<T> getExpressionList()
      Return the expression list that has been built for this query.
      String getGeneratedSql()
      Return the sql that was generated for executing this query.
      R having()
      Start adding expressions to the having clause when using @Aggregation properties.
      io.ebean.ExpressionList<T> havingClause()
      Return the underlying having clause to typically when using dynamic aggregation formula.
      R multiMatch​(String query, io.ebean.search.MultiMatch multiMatch)
      Add a Text Multi-match expression (document store only).
      R multiMatch​(String query, String... properties)
      Add a Text Multi-match expression (document store only).
      R must()
      Begin a list of expressions added by MUST.
      R mustNot()
      Begin a list of expressions added by MUST NOT.
      R not()
      Begin a list of expressions added by NOT.
      R or()
      Begin a list of expressions added by 'OR'.
      R order()
      Marker that can be used to indicate that the order by clause is defined after this.
      R order​(String orderByClause)
      Set the full raw order by clause replacing the existing order by clause if there is one.
      R orderBy()
      Marker that can be used to indicate that the order by clause is defined after this.
      R orderBy​(String orderByClause)
      Set the full raw order by clause replacing the existing order by clause if there is one.
      protected io.ebean.ExpressionList<T> peekExprList()
      Return the current expression list that expressions should be added to.
      io.ebean.Query<T> query()
      Return the underlying query.
      R raw​(String rawExpression)
      Add raw expression with no parameters.
      R raw​(String rawExpression, Object bindValue)
      Add raw expression with a single parameter.
      R raw​(String rawExpression, Object... bindValues)
      Add raw expression with an array of parameters.
      R rawOrEmpty​(String raw, Collection<?> values)
      Only add the raw expression if the values is not null or empty.
      R select​(io.ebean.FetchGroup<T> fetchGroup)
      Set a FetchGroup to control what part of the object graph is loaded.
      R select​(TQProperty<R>... properties)
      Tune the query by specifying the properties to be loaded on the 'main' root level entity bean (aka partial object).
      R select​(String properties)
      Explicitly set a comma delimited list of the properties to fetch on the 'main' root level entity bean (aka partial object).
      R setAllowLoadErrors()
      Execute the query allowing properties with invalid JSON to be collected and not fail the query.
      R setAutoTune​(boolean autoTune)
      Explicitly specify whether to use AutoTune for this query.
      R setBaseTable​(String baseTable)
      Set the base table to use for this query.
      R setBeanCacheMode​(io.ebean.CacheMode beanCacheMode)
      Set the mode to use the bean cache when executing this query.
      R setBufferFetchSizeHint​(int fetchSize)
      A hint which for JDBC translates to the Statement.fetchSize().
      R setDisableLazyLoading​(boolean disableLazyLoading)
      Set true if you want to disable lazy loading.
      R setDisableReadAuditing()
      Disable read auditing for this query.
      R setDistinct​(boolean distinct)
      Set whether this query uses DISTINCT.
      R setDocIndexName​(String indexName)
      Set the index(es) to search for a document store which uses partitions.
      R setFirstRow​(int firstRow)
      Set the first row to return for this query.
      R setId​(Object id)
      Set the Id value to query.
      R setIdIn​(Object... ids)
      Set a list of Id values to match.
      R setIdIn​(Collection<?> ids)
      Set a collection of Id values to match.
      R setIncludeSoftDeletes()
      Execute the query including soft deleted rows.
      R setInheritType​(Class<? extends T> type)
      Restrict the query to only return subtypes of the given inherit type.
      R setLabel​(String label)
      Set a label on the query.
      R setLazyLoadBatchSize​(int lazyLoadBatchSize)
      Set the default lazy loading batch size to use.
      R setLoadBeanCache​(boolean loadBeanCache)
      When set to true all the beans from this query are loaded into the bean cache.
      R setMapKey​(String mapKey)
      Set the property to use as keys for a map.
      R setMaxRows​(int maxRows)
      Set the maximum number of rows to return in the query.
      R setPersistenceContextScope​(io.ebean.PersistenceContextScope scope)
      Specify the PersistenceContextScope to use for this query.
      R setProfileLocation​(io.ebean.ProfileLocation profileLocation)
      Set the profile location.
      R setRawSql​(io.ebean.RawSql rawSql)
      Set RawSql to use for this query.
      R setReadOnly​(boolean readOnly)
      When set to true when you want the returned beans to be read only.
      protected void setRoot​(R root)
      Sets the root query bean instance.
      R setTimeout​(int secs)
      Set a timeout on this query.
      R setUseCache​(boolean useCache)
      Set this to true to use the bean cache.
      R setUseDocStore​(boolean useDocStore)
      Set to true if this query should execute against the doc store.
      R setUseQueryCache​(boolean useCache)
      Set this to true to use the query cache.
      R setUseQueryCache​(io.ebean.CacheMode cacheMode)
      Set the CacheMode to use the query for executing this query.
      R should()
      Begin a list of expressions added by SHOULD.
      R text()
      Begin added expressions to the 'Text' expression list.
      R textCommonTerms​(String query, io.ebean.search.TextCommonTerms options)
      Add a Text common terms expression (document store only).
      R textQueryString​(String query, io.ebean.search.TextQueryString options)
      Add a Text query string expression (document store only).
      R textSimple​(String query, io.ebean.search.TextSimple options)
      Add a Text simple expression (document store only).
      R usingConnection​(Connection connection)
      Execute the query using the given connection.
      R usingTransaction​(io.ebean.Transaction transaction)
      Execute the query using the given transaction.
      Set<String> validate()
      Returns the set of properties or paths that are unknown (do not map to known properties or paths).
      R where()
      Add expression after this to the WHERE expression list.
      R withLock​(io.ebean.Query.LockType lockType)
      Execute the query with the given lock type and WAIT.
      R withLock​(io.ebean.Query.LockType lockType, io.ebean.Query.LockWait lockWait)
      Execute the query with the given lock type and lock wait.
    • Constructor Detail

      • TQRootBean

        public TQRootBean​(Class<T> beanType)
        Construct using the type of bean to query on and the default database.
      • TQRootBean

        public TQRootBean​(Class<T> beanType,
                          io.ebean.Database database)
        Construct using the type of bean to query on and a given database.
      • TQRootBean

        protected TQRootBean​(Class<T> beanType,
                             io.ebean.Transaction transaction)
        Construct with a transaction.
      • TQRootBean

        protected TQRootBean​(Class<T> beanType,
                             io.ebean.Database database,
                             io.ebean.Transaction transaction)
        Construct with a database and transaction.
      • TQRootBean

        public TQRootBean​(io.ebean.Query<T> query)
        Construct using a query.
      • TQRootBean

        public TQRootBean​(boolean aliasDummy)
        Construct for using as an 'Alias' to use the properties as known string values for select() and fetch().
    • Method Detail

      • buildFetchGroup

        public io.ebean.FetchGroup<T> buildFetchGroup()
        Return the fetch group.
      • setRoot

        protected void setRoot​(R root)
        Sets the root query bean instance. Used to provide fluid query construction.
      • query

        public io.ebean.Query<T> query()
        Return the underlying query.

        Generally it is not expected that you will need to do this but typically use the find methods available on this 'root query bean' instance like findList().

      • select

        public R select​(String properties)
        Explicitly set a comma delimited list of the properties to fetch on the 'main' root level entity bean (aka partial object). Note that '*' means all properties.

        You use fetch(String, String) to specify specific properties to fetch on other non-root level paths of the object graph.

        
        
         List<Customer> customers =
             new QCustomer()
             // Only fetch the customer id, name and status.
             // This is described as a "Partial Object"
             .select("name, status")
             .name.ilike("rob%")
             .findList();
        
         
        Parameters:
        properties - the properties to fetch for this bean (* = all properties).
      • select

        public R select​(io.ebean.FetchGroup<T> fetchGroup)
        Set a FetchGroup to control what part of the object graph is loaded.

        FetchGroup is immutable and threadsafe. We expect to create and store FetchGroup to a static final field and reuse the instance.

        FetchGroup is an alternative to using select() and fetch() providing a nice clean separation between what a query should load and the query predicates.

        
        
         // immutable threadsafe
        
         static final FetchGroup<Customer> fetchGroup =
           QCustomer.forFetchGroup()
             .shippingAddress.fetch()
             .contacts.fetch()
             .buildFetchGroup();
        
         List<Customer> customers = new QCustomer()
           .select(fetchGroup)
           .findList();
        
         
        
        
         static final FetchGroup<Customer> fetchGroup =
           FetchGroup.of(Customer.class)
             .select("name, status")
             .fetch("contacts", "firstName, lastName, email")
             .build();
        
         List<Customer> customers = new QCustomer()
           .select(fetchGroup)
           .findList();
        
         
      • select

        @SafeVarargs
        public final R select​(TQProperty<R>... properties)
        Tune the query by specifying the properties to be loaded on the 'main' root level entity bean (aka partial object).
        
        
           // alias for the customer properties in select()
           QCustomer cust = QCustomer.alias();
        
           // alias for the contact properties in contacts.fetch()
           QContact contact = QContact.alias();
        
           List<Customer> customers =
             new QCustomer()
               // tune query
               .select(cust.id, cust.name)
               .contacts.fetch(contact.firstName, contact.lastName, contact.email)
        
               // predicates
               .id.greaterThan(1)
               .findList();
        
         
        Parameters:
        properties - the list of properties to fetch
      • fetch

        public R fetch​(String path)
        Specify a path to load including all its properties.
        
        
         List<Customer> customers =
             new QCustomer()
             // eager fetch the contacts
             .fetch("contacts")
             .findList();
        
         
        Parameters:
        path - the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean.
      • fetchQuery

        public R fetchQuery​(String path)
        Specify a path to load including all its properties using a "query join".
        
        
         List<Customer> customers =
             new QCustomer()
             // eager fetch the contacts using a "query join"
             .fetchQuery("contacts")
             .findList();
        
         
        Parameters:
        path - the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean.
      • fetchCache

        public R fetchCache​(String path)
        Specify a path to load from L2 cache including all its properties.
        
        
         List<Order> orders =
             new QOrder()
             // eager fetch the customer using L2 cache
             .fetchCache("customer")
             .findList();
        
         
        Parameters:
        path - the property path to load from L2 cache.
      • fetchQuery

        public R fetchQuery​(String path,
                            String properties)
        Specify a path and properties to load using a "query join".
        
        
         List<Customer> customers =
             new QCustomer()
             // eager fetch contacts using a "query join"
             .fetchQuery("contacts", "email, firstName, lastName")
             .findList();
        
         
        Parameters:
        path - the property path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean.
        properties - the properties to load for this path.
      • fetchCache

        public R fetchCache​(String path,
                            String properties)
        Specify a path and properties to load from L2 cache.
        
        
         List<Order> orders =
             new QOrder()
             // eager fetch the customer using L2 cache
             .fetchCache("customer", "name,status")
             .findList();
        
         
        Parameters:
        path - the property path to load from L2 cache.
        properties - the properties to load for this path.
      • fetch

        public R fetch​(String path,
                       String properties)
        Specify a path to fetch with its specific properties to include (aka partial object).

        When you specify a join this means that property (associated bean(s)) will be fetched and populated. If you specify "*" then all the properties of the associated bean will be fetched and populated. You can specify a comma delimited list of the properties of that associated bean which means that only those properties are fetched and populated resulting in a "Partial Object" - a bean that only has some of its properties populated.

        
        
         // query orders...
         List<Order> orders =
             new QOrder()
               .fetch("customer", "name, phoneNumber")
               .fetch("customer.billingAddress", "*")
               .findList();
        
         

        If columns is null or "*" then all columns/properties for that path are fetched.

        
        
         List<Customer> customers =
             new QCustomer()
             .select("name, status")
             .fetch("contacts", "firstName,lastName,email")
             .findList();
        
         
        Parameters:
        path - the path of an associated (OneToOne, OneToMany, ManyToOne or ManyToMany) bean.
        properties - properties of the associated bean that you want to include in the fetch (* means all properties, null also means all properties).
      • fetch

        public R fetch​(String path,
                       String properties,
                       io.ebean.FetchConfig fetchConfig)
        Additionally specify a FetchConfig to use a separate query or lazy loading to load this path.

        
        
         // fetch customers (their id, name and status)
         List<Customer> customers =
             new QCustomer()
             .select("name, status")
             .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10))
             .findList();
        
         
      • fetch

        public R fetch​(String path,
                       io.ebean.FetchConfig fetchConfig)
        Additionally specify a FetchConfig to specify a "query join" and or define the lazy loading query.

        
        
         // fetch customers (their id, name and status)
         List<Customer> customers =
             new QCustomer()
               // lazy fetch contacts with a batch size of 100
               .fetch("contacts", new FetchConfig().lazy(100))
               .findList();
        
         
      • apply

        public R apply​(io.ebean.text.PathProperties pathProperties)
        Apply the path properties replacing the select and fetch clauses.

        This is typically used when the PathProperties is applied to both the query and the JSON output.

      • asOf

        public R asOf​(Timestamp asOf)
        Perform an 'As of' query using history tables to return the object graph as of a time in the past.

        To perform this query the DB must have underlying history tables.

        Parameters:
        asOf - the date time in the past at which you want to view the data
      • asDraft

        public R asDraft()
        Execute the query against the draft set of tables.
      • setIncludeSoftDeletes

        public R setIncludeSoftDeletes()
        Execute the query including soft deleted rows.
      • alias

        public R alias​(String alias)
        Set root table alias.
      • setMaxRows

        public R setMaxRows​(int maxRows)
        Set the maximum number of rows to return in the query.
        Parameters:
        maxRows - the maximum number of rows to return in the query.
      • setFirstRow

        public R setFirstRow​(int firstRow)
        Set the first row to return for this query.
        Parameters:
        firstRow - the first row to include in the query result.
      • setAllowLoadErrors

        public R setAllowLoadErrors()
        Execute the query allowing properties with invalid JSON to be collected and not fail the query.
        
        
           // fetch a bean with JSON content
           EBasicJsonList bean= new QEBasicJsonList()
               .id.equalTo(42)
               .setAllowLoadErrors()  // collect errors into bean state if we have invalid JSON
               .findOne();
        
        
           // get the invalid JSON errors from the bean state
           Map<String, Exception> errors = server().getBeanState(bean).getLoadErrors();
        
           // If this map is not empty tell we have invalid JSON
           // and should try and fix the JSON content or inform the user
        
         
      • setAutoTune

        public R setAutoTune​(boolean autoTune)
        Explicitly specify whether to use AutoTune for this query.

        If you do not call this method on a query the "Implicit AutoTune mode" is used to determine if AutoTune should be used for a given query.

        AutoTune can add additional fetch paths to the query and specify which properties are included for each path. If you have explicitly defined some fetch paths AutoTune will not remove them.

      • setBufferFetchSizeHint

        public R setBufferFetchSizeHint​(int fetchSize)
        A hint which for JDBC translates to the Statement.fetchSize().

        Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet.

      • setDistinct

        public R setDistinct​(boolean distinct)
        Set whether this query uses DISTINCT.
      • setDocIndexName

        public R setDocIndexName​(String indexName)
        Set the index(es) to search for a document store which uses partitions.

        For example, when executing a query against ElasticSearch with daily indexes we can explicitly specify the indexes to search against.

        
        
           // explicitly specify the indexes to search
           query.setDocIndexName("logstash-2016.11.5,logstash-2016.11.6")
        
           // search today's index
           query.setDocIndexName("$today")
        
           // search the last 3 days
           query.setDocIndexName("$last-3")
        
         

        If the indexName is specified with ${daily} e.g. "logstash-${daily}" ... then we can use $today and $last-x as the search docIndexName like the examples below.

        
        
           // search today's index
           query.setDocIndexName("$today")
        
           // search the last 3 days
           query.setDocIndexName("$last-3")
        
         
        Parameters:
        indexName - The index or indexes to search against
        Returns:
        This query
      • setInheritType

        public R setInheritType​(Class<? extends T> type)
        Restrict the query to only return subtypes of the given inherit type.
        
        
           List<Animal> animals =
             new QAnimal()
               .name.startsWith("Fluffy")
               .setInheritType(Cat.class)
               .findList();
        
         
      • setBaseTable

        public R setBaseTable​(String baseTable)
        Set the base table to use for this query.

        Typically this is used when a table has partitioning and we wish to specify a specific partition/table to query against.

        
        
           QOrder()
           .setBaseTable("order_2019_05")
           .status.equalTo(Status.NEW)
           .findList();
        
         
      • withLock

        public R withLock​(io.ebean.Query.LockType lockType)
        Execute the query with the given lock type and WAIT.

        Note that forUpdate() is the same as withLock(LockType.UPDATE).

        Provides us with the ability to explicitly use Postgres SHARE, KEY SHARE, NO KEY UPDATE and UPDATE row locks.

      • withLock

        public R withLock​(io.ebean.Query.LockType lockType,
                          io.ebean.Query.LockWait lockWait)
        Execute the query with the given lock type and lock wait.

        Note that forUpdateNoWait() is the same as withLock(LockType.UPDATE, LockWait.NOWAIT).

        Provides us with the ability to explicitly use Postgres SHARE, KEY SHARE, NO KEY UPDATE and UPDATE row locks.

      • forUpdate

        public R forUpdate()
        Execute using "for update" clause which results in the DB locking the record.
      • forUpdateNoWait

        public R forUpdateNoWait()
        Execute using "for update" clause with "no wait" option.

        This is typically a Postgres and Oracle only option at this stage.

      • forUpdateSkipLocked

        public R forUpdateSkipLocked()
        Execute using "for update" clause with "skip locked" option.

        This is typically a Postgres and Oracle only option at this stage.

      • asUpdate

        public io.ebean.UpdateQuery<T> asUpdate()
        Return this query as an UpdateQuery.
        
        
           int rows =
             new QCustomer()
             .name.startsWith("Rob")
             .organisation.id.equalTo(42)
             .asUpdate()
               .set("active", false)
               .update()
        
         
        Returns:
        This query as an UpdateQuery
      • asDto

        public <D> io.ebean.DtoQuery<D> asDto​(Class<D> dtoClass)
        Convert the query to a DTO bean query.

        We effectively use the underlying ORM query to build the SQL and then execute and map it into DTO beans.

      • setId

        public R setId​(Object id)
        Set the Id value to query. This is used with findOne().

        You can use this to have further control over the query. For example adding fetch joins.

        
        
         Order order =
           new QOrder()
             .setId(1)
             .fetch("details")
             .findOne();
        
         // the order details were eagerly fetched
         List<OrderDetail> details = order.getDetails();
        
         
      • setIdIn

        public R setIdIn​(Object... ids)
        Set a list of Id values to match.

        
        
         List<Order> orders =
           new QOrder()
             .setIdIn(42, 43, 44)
             .findList();
        
         
      • setIdIn

        public R setIdIn​(Collection<?> ids)
        Set a collection of Id values to match.

        
        
         Collection<?> ids = ...
        
         List<Order> orders =
           new QOrder()
             .setIdIn(ids)
             .findList();
        
         
      • setLabel

        public R setLabel​(String label)
        Set a label on the query.

        This label can be used to help identify query performance metrics but we can also use profile location enhancement on Finders so for some that would be a better option.

      • setProfileLocation

        public R setProfileLocation​(io.ebean.ProfileLocation profileLocation)
        Set the profile location.

        This is typically set automatically via enhancement when profile location enhancement is turned on. It is generally not set by application code.

      • setLazyLoadBatchSize

        public R setLazyLoadBatchSize​(int lazyLoadBatchSize)
        Set the default lazy loading batch size to use.

        When lazy loading is invoked on beans loaded by this query then this sets the batch size used to load those beans.

        Parameters:
        lazyLoadBatchSize - the number of beans to lazy load in a single batch
      • setLoadBeanCache

        public R setLoadBeanCache​(boolean loadBeanCache)
        When set to true all the beans from this query are loaded into the bean cache.
      • setMapKey

        public R setMapKey​(String mapKey)
        Set the property to use as keys for a map.

        If no property is set then the id property is used.

        
        
         // Assuming sku is unique for products...
        
         Map<String,Product> productMap =
             new QProduct()
             // use sku for keys...
             .setMapKey("sku")
             .findMap();
        
         
        Parameters:
        mapKey - the property to use as keys for a map.
      • setPersistenceContextScope

        public R setPersistenceContextScope​(io.ebean.PersistenceContextScope scope)
        Specify the PersistenceContextScope to use for this query.

        When this is not set the 'default' configured on io.ebean.config.ServerConfig#setPersistenceContextScope(PersistenceContextScope) is used - this value defaults to PersistenceContextScope.TRANSACTION.

        Note that the same persistence Context is used for subsequent lazy loading and query join queries.

        Note that #findEach uses a 'per object graph' PersistenceContext so this scope is ignored for queries executed as #findIterate, #findEach, #findEachWhile.

        Parameters:
        scope - The scope to use for this query and subsequent lazy loading.
      • setRawSql

        public R setRawSql​(io.ebean.RawSql rawSql)
        Set RawSql to use for this query.
      • setReadOnly

        public R setReadOnly​(boolean readOnly)
        When set to true when you want the returned beans to be read only.
      • setUseCache

        public R setUseCache​(boolean useCache)
        Set this to true to use the bean cache.

        If the query result is in cache then by default this same instance is returned. In this sense it should be treated as a read only object graph.

      • setBeanCacheMode

        public R setBeanCacheMode​(io.ebean.CacheMode beanCacheMode)
        Set the mode to use the bean cache when executing this query.

        By default "find by id" and "find by natural key" will use the bean cache when bean caching is enabled. Setting this to false means that the query will not use the bean cache and instead hit the database.

        By default findList() with natural keys will not use the bean cache. In that case we need to explicitly use the bean cache.

      • setUseDocStore

        public R setUseDocStore​(boolean useDocStore)
        Set to true if this query should execute against the doc store.

        When setting this you may also consider disabling lazy loading.

      • setDisableLazyLoading

        public R setDisableLazyLoading​(boolean disableLazyLoading)
        Set true if you want to disable lazy loading.

        That is, once the object graph is returned further lazy loading is disabled.

      • setDisableReadAuditing

        public R setDisableReadAuditing()
        Disable read auditing for this query.

        This is intended to be used when the query is not a user initiated query and instead part of the internal processing in an application to load a cache or document store etc. In these cases we don't want the query to be part of read auditing.

      • setUseQueryCache

        public R setUseQueryCache​(boolean useCache)
        Set this to true to use the query cache.
      • setUseQueryCache

        public R setUseQueryCache​(io.ebean.CacheMode cacheMode)
        Set the CacheMode to use the query for executing this query.
      • setTimeout

        public R setTimeout​(int secs)
        Set a timeout on this query.

        This will typically result in a call to setQueryTimeout() on a preparedStatement. If the timeout occurs an exception will be thrown - this will be a SQLException wrapped up in a PersistenceException.

        Parameters:
        secs - the query timeout limit in seconds. Zero means there is no limit.
      • validate

        public Set<String> validate()
        Returns the set of properties or paths that are unknown (do not map to known properties or paths).

        Validate the query checking the where and orderBy expression paths to confirm if they represent valid properties or paths for the given bean type.

      • raw

        public R raw​(String rawExpression)
        Add raw expression with no parameters.

        When properties in the clause are fully qualified as table-column names then they are not translated. logical property name names (not fully qualified) will still be translated to their physical name.

        
        
           raw("orderQty < shipQty")
        
         

        Subquery example:

        
        
           .raw("t0.customer_id in (select customer_id from customer_group where group_id = any(?::uuid[]))", groupIds)
        
         
      • raw

        public R raw​(String rawExpression,
                     Object... bindValues)
        Add raw expression with an array of parameters.

        The raw expression should contain the same number of ? as there are parameters.

        When properties in the clause are fully qualified as table-column names then they are not translated. logical property name names (not fully qualified) will still be translated to their physical name.

      • rawOrEmpty

        public R rawOrEmpty​(String raw,
                            Collection<?> values)
        Only add the raw expression if the values is not null or empty.

        This is a pure convenience expression to make it nicer to deal with the pattern where we use raw() expression with a subquery and only want to add the subquery predicate when the collection of values is not empty.

        Without inOrEmpty()

        
        
           QCustomer query = new QCustomer() // add some predicates
             .status.equalTo(Status.NEW);
        
           // common pattern - we can use rawOrEmpty() instead
           if (orderIds != null && !orderIds.isEmpty()) {
             query.raw("t0.customer_id in (select o.customer_id from orders o where o.id in (?1))", orderIds);
           }
        
           query.findList();
        
         

        Using rawOrEmpty()

        Note that in the example below we use the ?1 bind parameter to get "parameter expansion" for each element in the collection.
        
        
           new QCustomer()
             .status.equalTo(Status.NEW)
             // only add the expression if orderIds is not empty
             .rawOrEmpty("t0.customer_id in (select o.customer_id from orders o where o.id in (?1))", orderIds);
             .findList();
        
         

        Postgres ANY

        With Postgres we would often use the SQL ANY expression and array parameter binding rather than IN.
        
        
           new QCustomer()
             .status.equalTo(Status.NEW)
             .rawOrEmpty("t0.customer_id in (select o.customer_id from orders o where o.id = any(?))", orderIds);
             .findList();
        
         

        Note that we need to cast the Postgres array for UUID types like:

        
        
           " ... = any(?::uuid[])"
        
         
        Parameters:
        raw - The raw expression that is typically a subquery
        values - The values which is typically a list or set of id values.
      • raw

        public R raw​(String rawExpression,
                     Object bindValue)
        Add raw expression with a single parameter.

        The raw expression should contain a single ? at the location of the parameter.

        When properties in the clause are fully qualified as table-column names then they are not translated. logical property name names (not fully qualified) will still be translated to their physical name.

        Example:

        
        
           // use a database function
           raw("add_days(orderDate, 10) < ?", someDate)
        
         

        Subquery example:

        
        
           .raw("t0.customer_id in (select customer_id from customer_group where group_id = any(?::uuid[]))", groupIds)
        
         
      • orderBy

        public R orderBy()
        Marker that can be used to indicate that the order by clause is defined after this.

        Example: order by customer name, order date

        
           List<Order> orders =
                  new QOrder()
                    .customer.name.ilike("rob")
                    .orderBy()
                      .customer.name.asc()
                      .orderDate.asc()
                    .findList();
        
         
      • order

        public R order()
        Marker that can be used to indicate that the order by clause is defined after this.

        Example: order by customer name, order date

        
           List<Order> orders =
                  new QOrder()
                    .customer.name.ilike("rob")
                    .orderBy()
                      .customer.name.asc()
                      .orderDate.asc()
                    .findList();
        
         
      • orderBy

        public R orderBy​(String orderByClause)
        Set the full raw order by clause replacing the existing order by clause if there is one.

        This follows SQL syntax using commas between each property with the optional asc and desc keywords representing ascending and descending order respectively.

      • order

        public R order​(String orderByClause)
        Set the full raw order by clause replacing the existing order by clause if there is one.

        This follows SQL syntax using commas between each property with the optional asc and desc keywords representing ascending and descending order respectively.

      • or

        public R or()
        Begin a list of expressions added by 'OR'.

        Use endOr() or endJunction() to stop added to OR and 'pop' to the parent expression list.

        Example

        This example uses an 'OR' expression list with an inner 'AND' expression list.

        
        
            List<Customer> customers =
                  new QCustomer()
                    .status.equalTo(Customer.Status.GOOD)
                    .or()
                      .id.greaterThan(1000)
                      .and()
                        .name.startsWith("super")
                        .registered.after(fiveDaysAgo)
                      .endAnd()
                    .endOr()
                    .orderBy().id.desc()
                    .findList();
        
         

        Resulting SQL where clause

        sql
        
            where t0.status = ?  and (t0.id > ?  or (t0.name like ?  and t0.registered > ? ) )
            order by t0.id desc;
        
            --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
        
         
      • and

        public R and()
        Begin a list of expressions added by 'AND'.

        Use endAnd() or endJunction() to stop added to AND and 'pop' to the parent expression list.

        Note that typically the AND expression is only used inside an outer 'OR' expression. This is because the top level expression list defaults to an 'AND' expression list.

        Example

        This example uses an 'OR' expression list with an inner 'AND' expression list.

        
        
            List<Customer> customers =
                  new QCustomer()
                    .status.equalTo(Customer.Status.GOOD)
                    .or() // OUTER 'OR'
                      .id.greaterThan(1000)
                      .and()  // NESTED 'AND' expression list
                        .name.startsWith("super")
                        .registered.after(fiveDaysAgo)
                        .endAnd()
                      .endOr()
                    .orderBy().id.desc()
                    .findList();
        
         

        Resulting SQL where clause

        sql
        
            where t0.status = ?  and (t0.id > ?  or (t0.name like ?  and t0.registered > ? ) )
            order by t0.id desc;
        
            --bind(GOOD,1000,super%,Wed Jul 22 00:00:00 NZST 2015)
        
         
      • not

        public R not()
        Begin a list of expressions added by NOT.

        Use endNot() or endJunction() to stop added to NOT and 'pop' to the parent expression list.

      • must

        public R must()
        Begin a list of expressions added by MUST.

        This automatically makes this query a document store query.

        Use endJunction() to stop added to MUST and 'pop' to the parent expression list.

      • mustNot

        public R mustNot()
        Begin a list of expressions added by MUST NOT.

        This automatically makes this query a document store query.

        Use endJunction() to stop added to MUST NOT and 'pop' to the parent expression list.

      • should

        public R should()
        Begin a list of expressions added by SHOULD.

        This automatically makes this query a document store query.

        Use endJunction() to stop added to SHOULD and 'pop' to the parent expression list.

      • endJunction

        public R endJunction()
        End a list of expressions added by 'OR'.
      • endOr

        public R endOr()
        End OR junction - synonym for endJunction().
      • endAnd

        public R endAnd()
        End AND junction - synonym for endJunction().
      • endNot

        public R endNot()
        End NOT junction - synonym for endJunction().
      • where

        public R where()
        Add expression after this to the WHERE expression list.

        For queries against the normal database (not the doc store) this has no effect.

        This is intended for use with Document Store / ElasticSearch where expressions can be put into either the "query" section or the "filter" section of the query. Full text expressions like MATCH are in the "query" section but many expression can be in either - expressions after the where() are put into the "filter" section which means that they don't add to the relevance and are also cache-able.

      • text

        public R text()
        Begin added expressions to the 'Text' expression list.

        This automatically makes the query a document store query.

        For ElasticSearch expressions added to 'text' go into the ElasticSearch 'query context' and expressions added to 'where' go into the ElasticSearch 'filter context'.

      • multiMatch

        public R multiMatch​(String query,
                            io.ebean.search.MultiMatch multiMatch)
        Add a Text Multi-match expression (document store only).

        This automatically makes the query a document store query.

      • multiMatch

        public R multiMatch​(String query,
                            String... properties)
        Add a Text Multi-match expression (document store only).

        This automatically makes the query a document store query.

      • textCommonTerms

        public R textCommonTerms​(String query,
                                 io.ebean.search.TextCommonTerms options)
        Add a Text common terms expression (document store only).

        This automatically makes the query a document store query.

      • textSimple

        public R textSimple​(String query,
                            io.ebean.search.TextSimple options)
        Add a Text simple expression (document store only).

        This automatically makes the query a document store query.

      • textQueryString

        public R textQueryString​(String query,
                                 io.ebean.search.TextQueryString options)
        Add a Text query string expression (document store only).

        This automatically makes the query a document store query.

      • usingTransaction

        public R usingTransaction​(io.ebean.Transaction transaction)
        Execute the query using the given transaction.
      • usingConnection

        public R usingConnection​(Connection connection)
        Execute the query using the given connection.
      • exists

        public boolean exists()
        Execute the query returning true if a row is found.

        The query is executed using max rows of 1 and will only select the id property. This method is really just a convenient way to optimise a query to perform a 'does a row exist in the db' check.

        Example using a query bean:

        
        
           boolean userExists =
             new QContact()
               .email.equalTo("rob@foo.com")
               .exists();
        
         

        Example:

        
        
           boolean userExists = query()
             .where().eq("email", "rob@foo.com")
             .exists();
        
         
        Returns:
        True if the query finds a matching row in the database
      • findOne

        @Nullable
        public T findOne()
        Execute the query returning either a single bean or null (if no matching bean is found).

        If more than 1 row is found for this query then a PersistenceException is thrown.

        This is useful when your predicates dictate that your query should only return 0 or 1 results.

        
        
         // assuming the sku of products is unique...
         Product product =
             new QProduct()
                 .sku.equalTo("aa113")
                 .findOne();
         ...
         

        It is also useful with finding objects by their id when you want to specify further join information to optimise the query.

        
        
         // Fetch order 42 and additionally fetch join its order details...
         Order order =
             new QOrder()
                 .fetch("details") // eagerly load the order details
                 .id.equalTo(42)
                 .findOne();
        
         // the order details were eagerly loaded
         List<OrderDetail> details = order.getDetails();
         ...
         
      • findOneOrEmpty

        public Optional<T> findOneOrEmpty()
        Execute the query returning an optional bean.
      • findList

        public List<T> findList()
        Execute the query returning the list of objects.

        This query will execute against the EbeanServer that was used to create it.

        
        
         List<Customer> customers =
             new QCustomer()
               .name.ilike("rob%")
               .findList();
        
         
        See Also:
        Query.findList()
      • findStream

        public Stream<T> findStream()
        Execute the query returning the result as a Stream.

        Note that this can support very large queries iterating any number of results. To do so internally it can use multiple persistence contexts.

        
        
          // use try with resources to ensure Stream is closed
        
          try (Stream<Customer> stream = query.findStream()) {
            stream
            .map(...)
            .collect(...);
          }
        
         
      • findSet

        public Set<T> findSet()
        Execute the query returning the set of objects.

        This query will execute against the EbeanServer that was used to create it.

        
        
         Set<Customer> customers =
             new QCustomer()
               .name.ilike("rob%")
               .findSet();
        
         
        See Also:
        Query.findSet()
      • findIds

        public <A> List<A> findIds()
        Execute the query returning the list of Id's.

        This query will execute against the EbeanServer that was used to create it.

        See Also:
        Query.findIds()
      • findMap

        public <K> Map<K,​T> findMap()
        Execute the query returning a map of the objects.

        This query will execute against the EbeanServer that was used to create it.

        You can use setMapKey() or asMapKey() to specify the property to be used as keys on the map. If one is not specified then the id property is used.

        
        
         Map<String, Product> map =
           new QProduct()
             .sku.asMapKey()
             .findMap();
        
         
        See Also:
        Query.findMap()
      • findIterate

        public io.ebean.QueryIterator<T> findIterate()
        Execute the query iterating over the results.

        Note that findIterate (and findEach and findEachWhile) uses a "per graph" persistence context scope and adjusts jdbc fetch buffer size for large queries. As such it is better to use findList for small queries.

        Remember that with QueryIterator you must call QueryIterator.close() when you have finished iterating the results (typically in a finally block).

        findEach() and findEachWhile() are preferred to findIterate() as they ensure the jdbc statement and resultSet are closed at the end of the iteration.

        This query will execute against the EbeanServer that was used to create it.

        
        
          Query<Customer> query =
            new QCustomer()
             .status.equalTo(Customer.Status.NEW)
             .orderBy()
               id.asc()
             .query();
        
          try (QueryIterator<Customer> it = query.findIterate()) {
            while (it.hasNext()) {
              Customer customer = it.next();
              // do something with customer ...
            }
          }
        
         
      • findSingleAttributeList

        public <A> List<A> findSingleAttributeList()
        Execute the query returning a list of values for a single property.

        Example

        
        
          List<String> names =
            new QCustomer()
              .setDistinct(true)
              .select(name)
              .findSingleAttributeList();
        
         
        Returns:
        the list of values for the selected property
      • findSingleAttribute

        public <A> A findSingleAttribute()
        Execute the query returning a single value for a single property.

        Example

        
        
          LocalDate maxDate =
            new QCustomer()
              .select("max(startDate)")
              .findSingleAttribute();
        
         
        Returns:
        the list of values for the selected property
      • findEach

        public void findEach​(Consumer<T> consumer)
        Execute the query processing the beans one at a time.

        This method is appropriate to process very large query results as the beans are consumed one at a time and do not need to be held in memory (unlike #findList #findSet etc)

        Note that internally Ebean can inform the JDBC driver that it is expecting larger resultSet and specifically for MySQL this hint is required to stop it's JDBC driver from buffering the entire resultSet. As such, for smaller resultSets findList() is generally preferable.

        Compared with #findEachWhile this will always process all the beans where as #findEachWhile provides a way to stop processing the query result early before all the beans have been read.

        This method is functionally equivalent to findIterate() but instead of using an iterator uses the Consumer interface which is better suited to use with closures.

        
        
          new QCustomer()
             .status.equalTo(Status.NEW)
             .orderBy().id.asc()
             .findEach((Customer customer) -> {
        
               // do something with customer
               System.out.println("-- visit " + customer);
             });
        
         
        Parameters:
        consumer - the consumer used to process the queried beans.
      • findEach

        public void findEach​(int batch,
                             Consumer<List<T>> consumer)
        Execute findEach streaming query batching the results for consuming.

        This query execution will stream the results and is suited to consuming large numbers of results from the database.

        Typically we use this batch consumer when we want to do further processing on the beans and want to do that processing in batch form, for example - 100 at a time.

        Parameters:
        batch - The number of beans processed in the batch
        consumer - Process the batch of beans
      • findEachWhile

        public void findEachWhile​(Predicate<T> consumer)
        Execute the query using callbacks to a visitor to process the resulting beans one at a time.

        This method is functionally equivalent to findIterate() but instead of using an iterator uses the Predicate interface which is better suited to use with closures.

        
        
          new QCustomer()
             .status.equalTo(Status.NEW)
             .orderBy().id.asc()
             .findEachWhile((Customer customer) -> {
        
               // do something with customer
               System.out.println("-- visit " + customer);
        
               // return true to continue processing or false to stop
               return (customer.getId() < 40);
             });
        
         
        Parameters:
        consumer - the consumer used to process the queried beans.
      • findVersions

        public List<io.ebean.Version<T>> findVersions()
        Return versions of a @History entity bean.

        Generally this query is expected to be a find by id or unique predicates query. It will execute the query against the history returning the versions of the bean.

      • findVersionsBetween

        public List<io.ebean.Version<T>> findVersionsBetween​(Timestamp start,
                                                             Timestamp end)
        Return versions of a @History entity bean between a start and end timestamp.

        Generally this query is expected to be a find by id or unique predicates query. It will execute the query against the history returning the versions of the bean.

      • findCount

        public int findCount()
        Return the count of entities this query should return.

        This is the number of 'top level' or 'root level' entities.

      • findFutureCount

        public io.ebean.FutureRowCount<T> findFutureCount()
        Execute find row count query in a background thread.

        This returns a Future object which can be used to cancel, check the execution status (isDone etc) and get the value (with or without a timeout).

        Returns:
        a Future object for the row count query
      • findFutureIds

        public io.ebean.FutureIds<T> findFutureIds()
        Execute find Id's query in a background thread.

        This returns a Future object which can be used to cancel, check the execution status (isDone etc) and get the value (with or without a timeout).

        Returns:
        a Future object for the list of Id's
      • findFutureList

        public io.ebean.FutureList<T> findFutureList()
        Execute find list query in a background thread.

        This query will execute in it's own PersistenceContext and using its own transaction. What that means is that it will not share any bean instances with other queries.

        Returns:
        a Future object for the list result of the query
      • findPagedList

        public io.ebean.PagedList<T> findPagedList()
        Return a PagedList for this query using firstRow and maxRows.

        The benefit of using this over findList() is that it provides functionality to get the total row count etc.

        If maxRows is not set on the query prior to calling findPagedList() then a PersistenceException is thrown.

        
        
          PagedList<Order> pagedList =
            new QOrder()
               .setFirstRow(50)
               .setMaxRows(20)
               .findPagedList();
        
               // fetch the total row count in the background
               pagedList.loadRowCount();
        
               List<Order> orders = pagedList.getList();
               int totalRowCount = pagedList.getTotalRowCount();
        
         
        Returns:
        The PagedList
      • delete

        public int delete()
        Execute as a delete query deleting the 'root level' beans that match the predicates in the query.

        Note that if the query includes joins then the generated delete statement may not be optimal depending on the database platform.

        Returns:
        the number of beans/rows that were deleted.
      • getGeneratedSql

        public String getGeneratedSql()
        Return the sql that was generated for executing this query.

        This is only available after the query has been executed and provided only for informational purposes.

      • getBeanType

        public Class<T> getBeanType()
        Return the type of beans being queried.
      • getExpressionList

        public io.ebean.ExpressionList<T> getExpressionList()
        Return the expression list that has been built for this query.
      • having

        public R having()
        Start adding expressions to the having clause when using @Aggregation properties.
        
        
           new QMachineUse()
           // where ...
           .date.inRange(fromDate, toDate)
        
           .having()
           .sumHours.greaterThan(1)
           .findList()
        
           // The sumHours property uses @Aggregation
           // e.g. @Aggregation("sum(hours)")
        
         
      • havingClause

        public io.ebean.ExpressionList<T> havingClause()
        Return the underlying having clause to typically when using dynamic aggregation formula.

        Note that after this we no longer have the query bean so typically we use this right at the end of the query.

        
        
          // sum(distanceKms) ... is a "dynamic formula"
          // so we use havingClause() for it like:
        
          List<MachineUse> machineUse =
        
            new QMachineUse()
              .select("machine, sum(fuelUsed), sum(distanceKms)")
        
              // where ...
              .date.greaterThan(LocalDate.now().minusDays(7))
        
              .havingClause()
                .gt("sum(distanceKms)", 2)
                .findList();
        
         
      • peekExprList

        protected io.ebean.ExpressionList<T> peekExprList()
        Return the current expression list that expressions should be added to.
      • _peekText

        protected io.ebean.ExpressionList<T> _peekText()