Class DefaultOrmQuery<T>

    • Method Detail

      • asDto

        public <D> DtoQuery<D> asDto​(Class<D> dtoClass)
        Description copied from interface: Query
        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.

        Specified by:
        asDto in interface Query<T>
      • asUpdate

        public UpdateQuery<TasUpdate()
        Description copied from interface: Query
        Convert the query to a UpdateQuery.

        Typically this is used with query beans to covert a query bean query into an UpdateQuery like the examples below.

        
        
          int rowsUpdated = new QCustomer()
               .name.startsWith("Rob")
               .asUpdate()
               .set("active", false)
               .update();;
        
         
        
        
           int rowsUpdated = new QContact()
               .notes.note.startsWith("Make Inactive")
               .email.endsWith("@foo.com")
               .customer.id.equalTo(42)
               .asUpdate()
               .set("inactive", true)
               .setRaw("email = lower(email)")
               .update();
        
         
        Specified by:
        asUpdate in interface Query<T>
      • isFindAll

        public boolean isFindAll()
        Description copied from interface: SpiQuery
        Return true if this is a "find all" query. Used to set a "find all" profile location if necessary.
        Specified by:
        isFindAll in interface SpiQuery<T>
      • isFindById

        public boolean isFindById()
        Description copied from interface: SpiQuery
        Return true if this is a "find by id" query. This includes a check for a single "equal to" expression for the Id.
        Specified by:
        isFindById in interface SpiQuery<T>
      • setLabel

        public Query<TsetLabel​(String label)
        Description copied from interface: Query
        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.

        Specified by:
        setLabel in interface Query<T>
      • setUseDocStore

        public DefaultOrmQuery<TsetUseDocStore​(boolean useDocStore)
        Description copied from interface: Query
        Set to true if this query should execute against the doc store.

        When setting this you may also consider disabling lazy loading.

        Specified by:
        setUseDocStore in interface Query<T>
      • isUseDocStore

        public boolean isUseDocStore()
        Description copied from interface: SpiQuery
        Return true if this query should be executed against the doc store.
        Specified by:
        isUseDocStore in interface SpiQuery<T>
      • apply

        public Query<Tapply​(FetchPath fetchPath)
        Description copied from interface: Query
        Apply the path properties replacing the select and fetch clauses.

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

        Specified by:
        apply in interface Query<T>
      • setAllowLoadErrors

        public DefaultOrmQuery<TsetAllowLoadErrors()
        Description copied from interface: Query
        Execute the query allowing properties with invalid JSON to be collected and not fail the query.
        
        
           // fetch a bean with JSON content
           EBasicJsonList bean= DB.find(EBasicJsonList.class)
               .setId(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
        
         
        Specified by:
        setAllowLoadErrors in interface Query<T>
      • asOf

        public DefaultOrmQuery<TasOf​(Timestamp asOfDateTime)
        Description copied from interface: Query
        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.

        Specified by:
        asOf in interface Query<T>
        Parameters:
        asOfDateTime - the date time in the past at which you want to view the data
      • setIncludeSoftDeletes

        public DefaultOrmQuery<TsetIncludeSoftDeletes()
        Description copied from interface: Query
        Execute the query including soft deleted rows.

        This means that Ebean will not add any predicates to the query for filtering out soft deleted rows. You can still add your own predicates for the deleted properties and effectively you have full control over the query to include or exclude soft deleted rows as needed for a given use case.

        Specified by:
        setIncludeSoftDeletes in interface Query<T>
      • setDocIndexName

        public Query<TsetDocIndexName​(String indexName)
        Description copied from interface: Query
        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")
        
         
        Specified by:
        setDocIndexName in interface Query<T>
        Parameters:
        indexName - The index or indexes to search against
        Returns:
        This query
      • getDocIndexName

        public String getDocIndexName()
        Description copied from interface: SpiQuery
        For doc store query return the document index name to search against. This is for partitioned indexes (like daily logstash indexes etc).
        Specified by:
        getDocIndexName in interface SpiQuery<T>
      • setLazyLoadBatchSize

        public Query<TsetLazyLoadBatchSize​(int lazyLoadBatchSize)
        Description copied from interface: Query
        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.

        Specified by:
        setLazyLoadBatchSize in interface Query<T>
        Parameters:
        lazyLoadBatchSize - the number of beans to lazy load in a single batch
      • setDetail

        public void setDetail​(OrmQueryDetail detail)
        Description copied from interface: SpiQuery
        Replace the query detail. This is used by the AutoTune feature to as a fast way to set the query properties and joins.

        Note care must be taken to keep the where, orderBy, firstRows and maxRows held in the detail attributes.

        Specified by:
        setDetail in interface SpiQuery<T>
      • filterMany

        public ExpressionList<TfilterMany​(String prop)
        Description copied from interface: Query
        This applies a filter on the 'many' property list rather than the root level objects.

        Typically you will use this in a scenario where the cardinality is high on the 'many' property you wish to join to. Say you want to fetch customers and their associated orders... but instead of getting all the orders for each customer you only want to get the new orders they placed since last week. In this case you can use filterMany() to filter the orders.

        
        
         List<Customer> list = DB.find(Customer.class)
             .fetch("orders")
             .where().ilike("name", "rob%")
             .filterMany("orders").eq("status", Order.Status.NEW).gt("orderDate", lastWeek)
             .findList();
        
         

        Please note you have to be careful that you add expressions to the correct expression list - as there is one for the 'root level' and one for each filterMany that you have.

        Specified by:
        filterMany in interface Query<T>
        Parameters:
        prop - the name of the many property that you want to have a filter on.
        Returns:
        the expression list that you add filter expressions for the many to.
      • isWithId

        public boolean isWithId()
        Return true if the Id should be included in the query.
        Specified by:
        isWithId in interface SpiQuery<T>
      • setPersistenceContext

        public void setPersistenceContext​(PersistenceContext persistenceContext)
        Set an explicit TransactionContext (typically for a refresh query).

        If no TransactionContext is present on the query then the TransactionContext from the Transaction is used (transaction scoped persistence context).

        Specified by:
        setPersistenceContext in interface SpiQuery<T>
      • isAutoTuned

        public boolean isAutoTuned()
        Description copied from interface: Query
        Returns true if this query was tuned by autoTune.
        Specified by:
        isAutoTuned in interface Query<T>
      • setAutoTuned

        public void setAutoTuned​(boolean autoTuned)
        Description copied from interface: SpiQuery
        Set to true if this query has been tuned by autoTune.
        Specified by:
        setAutoTuned in interface SpiQuery<T>
      • isAutoTune

        public Boolean isAutoTune()
        Description copied from interface: SpiQuery
        Return explicit AutoTune setting or null. If null then not explicitly set so we use the default behaviour.
        Specified by:
        isAutoTune in interface SpiQuery<T>
      • setAutoTune

        public DefaultOrmQuery<TsetAutoTune​(boolean autoTune)
        Description copied from interface: Query
        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.

        Specified by:
        setAutoTune in interface Query<T>
      • isForUpdate

        public boolean isForUpdate()
        Description copied from interface: Query
        Return true if this query has forUpdate set.
        Specified by:
        isForUpdate in interface Query<T>
      • isAsDraft

        public boolean isAsDraft()
        Description copied from interface: SpiQuery
        Return true if this is a 'As Draft' query.
        Specified by:
        isAsDraft in interface SpiQuery<T>
      • isUsageProfiling

        public boolean isUsageProfiling()
        Description copied from interface: SpiQuery
        Return false when this is a lazy load or refresh query for a bean.

        We just take/copy the data from those beans and don't collect AutoTune usage profiling on those lazy load or refresh beans.

        Specified by:
        isUsageProfiling in interface SpiQuery<T>
      • setUsageProfiling

        public void setUsageProfiling​(boolean usageProfiling)
        Description copied from interface: SpiQuery
        Set to false if this query should not be included in the AutoTune usage profiling information.
        Specified by:
        setUsageProfiling in interface SpiQuery<T>
      • setParentNode

        public void setParentNode​(ObjectGraphNode parentNode)
        Description copied from interface: SpiQuery
        Set the profile point of the bean or collection that is lazy loading.

        This enables use to hook this back to the original 'root' query by the queryPlanHash and stackPoint.

        Specified by:
        setParentNode in interface SpiQuery<T>
      • setOrigin

        public ObjectGraphNode setOrigin​(CallOrigin callOrigin)
        Description copied from interface: SpiQuery
        Return the origin point for the query.

        This MUST be call prior to a query being changed via tuning. This is because the queryPlanHash is used to identify the query point.

        Specified by:
        setOrigin in interface SpiQuery<T>
      • queryBindHash

        public int queryBindHash()
        Calculate a hash based on the bind values used in the query.

        Used with queryPlanHash() to get a unique hash for a query.

        Specified by:
        queryBindHash in interface SpiQuery<T>
      • queryHash

        public HashQuery queryHash()
        Return a hash that includes the query plan and bind values.

        This hash can be used to identify if we have executed the exact same query (including bind values) before.

        Specified by:
        queryHash in interface SpiQuery<T>
      • isRawSql

        public boolean isRawSql()
        Description copied from interface: SpiQuery
        Return true if this is a RawSql query.
        Specified by:
        isRawSql in interface SpiQuery<T>
      • setBeanCacheMode

        public Query<TsetBeanCacheMode​(CacheMode beanCacheMode)
        Description copied from interface: Query
        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.

        Specified by:
        setBeanCacheMode in interface Query<T>
      • setLoadBeanCache

        public DefaultOrmQuery<TsetLoadBeanCache​(boolean loadBeanCache)
        Description copied from interface: Query
        Will be deprecated - migrate to use setBeanCacheMode(CacheMode.RECACHE).

        When set to true all the beans from this query are loaded into the bean cache.

        Specified by:
        setLoadBeanCache in interface Query<T>
      • setTimeout

        public DefaultOrmQuery<TsetTimeout​(int secs)
        Description copied from interface: Query
        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.

        Specified by:
        setTimeout in interface Query<T>
        Parameters:
        secs - the query timeout limit in seconds. Zero means there is no limit.
      • select

        public DefaultOrmQuery<Tselect​(String columns)
        Description copied from interface: Query
        Specify the properties to fetch on the root level entity bean in comma delimited format.

        The Id property is automatically included in the properties to fetch unless setDistinct(true) is set on the query.

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

        
        
         List<Customer> customers = DB.find(Customer.class)
             // Only fetch the customer id, name and status.
             // This is described as a "Partial Object"
             .select("name, status")
             .where.ilike("name", "rob%")
             .findList();
        
         
        Specified by:
        select in interface Query<T>
        Parameters:
        columns - the properties to fetch for this bean (* = all properties).
      • fetch

        public DefaultOrmQuery<Tfetch​(String property)
        Description copied from interface: Query
        Specify a path to fetch eagerly including all its properties.

        Ebean will endeavour to fetch this path using a SQL join. If Ebean determines that it can not use a SQL join (due to maxRows or because it would result in a cartesian product) Ebean will automatically convert this fetch query into a "query join" - i.e. use fetchQuery().

        
        
         // fetch customers (their id, name and status)
         List<Customer> customers = DB.find(Customer.class)
             // eager fetch the contacts
             .fetch("contacts")
             .findList();
        
         
        Specified by:
        fetch in interface Query<T>
        Parameters:
        property - the property path we wish to fetch eagerly.
      • fetchQuery

        public Query<TfetchQuery​(String property)
        Description copied from interface: Query
        Fetch the path eagerly using a "query join" (separate SQL query).

        This is the same as:

        
        
          fetch(path, new FetchConfig().query())
        
         

        This would be used instead of a fetch() when we use a separate SQL query to fetch this part of the object graph rather than a SQL join.

        We might typically get a performance benefit when the path to fetch is a OneToMany or ManyToMany, the 'width' of the 'root bean' is wide and the cardinality of the many is high.

        Specified by:
        fetchQuery in interface Query<T>
        Parameters:
        property - the property path we wish to fetch eagerly
      • fetchLazy

        public Query<TfetchLazy​(String property)
        Description copied from interface: Query
        Fetch the path lazily (via batch lazy loading).

        This is the same as:

        
        
          fetch(path, new FetchConfig().lazy())
        
         

        The reason for using fetchLazy() is to either:

        • Control/tune what is fetched as part of lazy loading
        • Make use of the L2 cache, build this part of the graph from L2 cache
        Specified by:
        fetchLazy in interface Query<T>
        Parameters:
        property - the property path we wish to fetch lazily.
      • fetch

        public DefaultOrmQuery<Tfetch​(String property,
                                        FetchConfig joinConfig)
        Description copied from interface: Query
        Additionally specify a JoinConfig to specify a "query join" and or define the lazy loading query.
        
        
         // fetch customers (their id, name and status)
         List<Customer> customers = DB.find(Customer.class)
             // lazy fetch contacts with a batch size of 100
             .fetch("contacts", new FetchConfig().lazy(100))
             .findList();
        
         
        Specified by:
        fetch in interface Query<T>
      • fetch

        public DefaultOrmQuery<Tfetch​(String property,
                                        String columns)
        Description copied from interface: Query
        Specify a path to fetch eagerly including specific properties.

        Ebean will endeavour to fetch this path using a SQL join. If Ebean determines that it can not use a SQL join (due to maxRows or because it would result in a cartesian product) Ebean will automatically convert this fetch query into a "query join" - i.e. use fetchQuery().

        
        
         // query orders...
         List<Order> orders = DB.find(Order.class)
               // fetch the customer...
               // ... getting the customers name and phone number
               .fetch("customer", "name, phoneNumber")
        
               // ... also fetch the customers billing address (* = all properties)
               .fetch("customer.billingAddress", "*")
               .findList();
         

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

        
        
         // fetch customers (their id, name and status)
         List<Customer> customers = DB.find(Customer.class)
             .select("name, status")
             .fetch("contacts", "firstName,lastName,email")
             .findList();
        
         
        Specified by:
        fetch in interface Query<T>
        Parameters:
        property - the property path we wish to fetch eagerly.
        columns - properties of the associated bean that you want to include in the fetch (* means all properties, null also means all properties).
      • fetchQuery

        public Query<TfetchQuery​(String property,
                                   String columns)
        Description copied from interface: Query
        Fetch the path and properties using a "query join" (separate SQL query).

        This is the same as:

        
        
          fetch(path, fetchProperties, new FetchConfig().query())
        
         

        This would be used instead of a fetch() when we use a separate SQL query to fetch this part of the object graph rather than a SQL join.

        We might typically get a performance benefit when the path to fetch is a OneToMany or ManyToMany, the 'width' of the 'root bean' is wide and the cardinality of the many is high.

        Specified by:
        fetchQuery in interface Query<T>
        Parameters:
        property - the property path we wish to fetch eagerly.
        columns - properties of the associated bean that you want to include in the fetch (* means all properties, null also means all properties).
      • fetchCache

        public Query<TfetchCache​(String property,
                                   String columns)
        Description copied from interface: Query
        Fetch the path and properties using L2 bean cache.
        Specified by:
        fetchCache in interface Query<T>
        Parameters:
        property - The path of the beans we are fetching from L2 cache.
        columns - The properties that should be loaded.
      • fetchLazy

        public Query<TfetchLazy​(String property,
                                  String columns)
        Description copied from interface: Query
        Fetch the path and properties lazily (via batch lazy loading).

        This is the same as:

        
        
          fetch(path, fetchProperties, new FetchConfig().lazy())
        
         

        The reason for using fetchLazy() is to either:

        • Control/tune what is fetched as part of lazy loading
        • Make use of the L2 cache, build this part of the graph from L2 cache
        Specified by:
        fetchLazy in interface Query<T>
        Parameters:
        property - the property path we wish to fetch lazily.
        columns - properties of the associated bean that you want to include in the fetch (* means all properties, null also means all properties).
      • fetch

        public DefaultOrmQuery<Tfetch​(String property,
                                        String columns,
                                        FetchConfig config)
        Description copied from interface: Query
        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 = DB.find(Customer.class)
             .select("name, status")
             .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10))
             .findList();
        
         
        Specified by:
        fetch in interface Query<T>
        Parameters:
        property - the property path we wish to fetch eagerly.
      • delete

        public int delete()
        Description copied from interface: Query
        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.

        Specified by:
        delete in interface Query<T>
        Returns:
        the number of beans/rows that were deleted.
      • delete

        public int delete​(Transaction transaction)
        Description copied from interface: Query
        Execute as a delete query returning the number of rows deleted using the given transaction.

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

        Specified by:
        delete in interface Query<T>
        Returns:
        the number of beans/rows that were deleted.
      • update

        public int update()
        Description copied from interface: Query
        Execute the UpdateQuery returning the number of rows updated.
        Specified by:
        update in interface Query<T>
        Returns:
        the number of beans/rows updated.
      • update

        public int update​(Transaction transaction)
        Description copied from interface: Query
        Execute the UpdateQuery returning the number of rows updated using the given transaction.
        Specified by:
        update in interface Query<T>
        Returns:
        the number of beans/rows updated.
      • findIds

        public <A> List<A> findIds()
        Description copied from interface: Query
        Execute the query returning the list of Id's.

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

        Specified by:
        findIds in interface Query<T>
      • exists

        public boolean exists()
        Description copied from interface: Query
        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("[email protected]")
               .exists();
        
         

        Example:

        
        
           boolean userExists = query()
             .where().eq("email", "[email protected]")
             .exists();
        
         
        Specified by:
        exists in interface Query<T>
        Returns:
        True if the query finds a matching row in the database
      • findCount

        public int findCount()
        Description copied from interface: Query
        Return the count of entities this query should return.

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

        Specified by:
        findCount in interface Query<T>
      • findEachWhile

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

        Note that findEachWhile (and findEach and findIterate) 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.

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

        
        
          DB.find(Customer.class)
             .fetch("contacts", new FetchConfig().query(2))
             .where().eq("status", Status.NEW)
             .order().asc("id")
             .setMaxRows(2000)
             .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);
             });
        
         
        Specified by:
        findEachWhile in interface Query<T>
        Parameters:
        consumer - the consumer used to process the queried beans.
      • findEach

        public void findEach​(Consumer<T> consumer)
        Description copied from interface: Query
        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 findEach (and findEachWhile and findIterate) 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.

        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 Java8 closures.

        
        
          DB.find(Customer.class)
             .where().eq("status", Status.NEW)
             .order().asc("id")
             .findEach((Customer customer) -> {
        
               // do something with customer
               System.out.println("-- visit " + customer);
             });
        
         
        Specified by:
        findEach in interface Query<T>
        Parameters:
        consumer - the consumer used to process the queried beans.
      • findIterate

        public QueryIterator<TfindIterate()
        Description copied from interface: Query
        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 Database that was used to create it.

        
        
          Query<Customer> query = DB.find(Customer.class)
             .where().eq("status", Status.NEW)
             .order().asc("id");
        
          // use try with resources to ensure QueryIterator is closed
        
          try (QueryIterator<Customer> it = query.findIterate()) {
            while (it.hasNext()) {
              Customer customer = it.next();
              // do something with customer ...
            }
          }
        
         
        Specified by:
        findIterate in interface Query<T>
      • findStream

        public Stream<TfindStream()
        Description copied from interface: Query
        Execute the query returning the result as a Stream.

        Note that this will hold all resulting beans in memory using a single persistence context. Use findLargeStream() for queries that expect to return a large number of results.

        
        
          // use try with resources to ensure Stream is closed
        
          try (Stream<Customer> stream = query.findStream()) {
            stream
            .map(...)
            .collect(...);
          }
        
         
        Specified by:
        findStream in interface Query<T>
      • findLargeStream

        public Stream<TfindLargeStream()
        Description copied from interface: Query
        Execute the query returning the result as a Stream.

        Note that this uses multiple persistence contexts such that we can use it with a large number of results.

        
        
          // use try with resources to ensure Stream is closed
        
          try (Stream<Customer> stream = query.findLargeStream()) {
            stream
            .map(...)
            .collect(...);
          }
        
         
        Specified by:
        findLargeStream in interface Query<T>
      • findVersions

        public List<Version<T>> findVersions()
        Description copied from interface: Query
        Return versions of a @History entity bean.

        Note that this query will work against view based history implementations but not sql2011 standards based implementations that require a start and end timestamp to be specified.

        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.

        Specified by:
        findVersions in interface Query<T>
      • findVersionsBetween

        public List<Version<T>> findVersionsBetween​(Timestamp start,
                                                    Timestamp end)
        Description copied from interface: Query
        Return versions of a @History entity bean between the 2 timestamps.

        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.

        Specified by:
        findVersionsBetween in interface Query<T>
      • findList

        public List<TfindList()
        Description copied from interface: Query
        Execute the query returning the list of objects.

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

        
        
         List<Customer> customers = DB.find(Customer.class)
             .where().ilike("name", "rob%")
             .findList();
        
         
        Specified by:
        findList in interface Query<T>
      • findSet

        public Set<TfindSet()
        Description copied from interface: Query
        Execute the query returning the set of objects.

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

        
        
         Set<Customer> customers = DB.find(Customer.class)
             .where().ilike("name", "rob%")
             .findSet();
        
         
        Specified by:
        findSet in interface Query<T>
      • findMap

        public <K> Map<K,​TfindMap()
        Description copied from interface: Query
        Execute the query returning a map of the objects.

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

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

        
        
         Map<String, Product> map = DB.find(Product.class)
             .setMapKey("sku")
             .findMap();
        
         
        Specified by:
        findMap in interface Query<T>
      • findSingleAttributeList

        public <A> List<A> findSingleAttributeList()
        Description copied from interface: Query
        Execute the query returning a list of values for a single property.

        Example 1:

        
        
          List<String> names =
            DB.find(Customer.class)
              .select("name")
              .order().asc("name")
              .findSingleAttributeList();
        
         

        Example 2:

        
        
          List<String> names =
            DB.find(Customer.class)
              .setDistinct(true)
              .select("name")
              .where().eq("status", Customer.Status.NEW)
              .order().asc("name")
              .setMaxRows(100)
              .findSingleAttributeList();
        
         
        Specified by:
        findSingleAttributeList in interface Query<T>
        Returns:
        the list of values for the selected property
      • findSingleAttribute

        public <A> A findSingleAttribute()
        Description copied from interface: Query
        Execute a query returning a single value of a single property/column.

        
        
          String name =
            DB.find(Customer.class)
              .select("name")
              .where().eq("id", 42)
              .findSingleAttribute();
        
         
        Specified by:
        findSingleAttribute in interface Query<T>
      • findOne

        public T findOne()
        Description copied from interface: Query
        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 NonUniqueResultException 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 = DB.find(Product.class)
                 .where().eq("sku", "aa113")
                 .findOne();
         ...
         

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

        
        
         // Fetch order 1 and additionally fetch join its order details...
         Order order = DB.find(Order.class)
               .setId(1)
               .fetch("details")
               .findOne();
        
         // the order details were eagerly loaded
         List<OrderDetail> details = order.getDetails();
         ...
         
        Specified by:
        findOne in interface Query<T>
      • findFutureIds

        public FutureIds<TfindFutureIds()
        Description copied from interface: Query
        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).

        Specified by:
        findFutureIds in interface Query<T>
        Returns:
        a Future object for the list of Id's
      • findFutureList

        public FutureList<TfindFutureList()
        Description copied from interface: Query
        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.

        Specified by:
        findFutureList in interface Query<T>
        Returns:
        a Future object for the list result of the query
      • findFutureCount

        public FutureRowCount<TfindFutureCount()
        Description copied from interface: Query
        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).

        Specified by:
        findFutureCount in interface Query<T>
        Returns:
        a Future object for the row count query
      • findPagedList

        public PagedList<TfindPagedList()
        Description copied from interface: Query
        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 = DB.find(Order.class)
               .setFirstRow(50)
               .setMaxRows(20)
               .findPagedList();
        
               // fetch the total row count in the background
               pagedList.loadRowCount();
        
               List<Order> orders = pagedList.getList();
               int totalRowCount = pagedList.getTotalRowCount();
        
         
        Specified by:
        findPagedList in interface Query<T>
        Returns:
        The PagedList
      • setParameter

        public DefaultOrmQuery<TsetParameter​(Object value)
        Description copied from interface: Query
        Bind the next positioned parameter.
        
        
         // a query with a positioned parameters
         String oql = "where status = ? and name = ?";
        
         List<Order> list = DB.createQuery(Order.class, oql)
           .setParameter(OrderStatus.NEW)
           .setParameter("Rob")
           .findList();
        
         
        Specified by:
        setParameter in interface Query<T>
      • setParameter

        public DefaultOrmQuery<TsetParameter​(int position,
                                               Object value)
        Set an ordered bind parameter according to its position. Note that the position starts at 1 to be consistent with JDBC PreparedStatement. You need to set a parameter value for each ? you have in the query.
        Specified by:
        setParameter in interface Query<T>
        Parameters:
        position - the parameter bind position starting from 1 (not 0)
        value - the parameter bind value.
      • orderBy

        @Deprecated
        public OrderBy<TorderBy()
        Deprecated.
        Description copied from interface: Query
        Return the OrderBy so that you can append an ascending or descending property to the order by clause.

        This will never return a null. If no order by clause exists then an 'empty' OrderBy object is returned.

        This is the same as order()

        Specified by:
        orderBy in interface Query<T>
      • order

        public OrderBy<Torder()
        Description copied from interface: Query
        Return the OrderBy so that you can append an ascending or descending property to the order by clause.

        This will never return a null. If no order by clause exists then an 'empty' OrderBy object is returned.

        This is the same as orderBy()

        Specified by:
        order in interface Query<T>
      • orderBy

        @Deprecated
        public DefaultOrmQuery<TorderBy​(String orderByClause)
        Deprecated.
        Description copied from interface: Query
        Set the 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.

        Specified by:
        orderBy in interface Query<T>
      • order

        public DefaultOrmQuery<Torder​(String orderByClause)
        Description copied from interface: Query
        Set the 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.

        Specified by:
        order in interface Query<T>
      • isManualId

        public boolean isManualId()
        Description copied from interface: SpiQuery
        Return true if the Id property is manually included in the query (DTO queries).
        Specified by:
        isManualId in interface SpiQuery<T>
      • setManualId

        public void setManualId()
        Description copied from interface: SpiQuery
        Set to true when we only include the Id property if it is explicitly included in the select().
        Specified by:
        setManualId in interface SpiQuery<T>
      • isDistinct

        public boolean isDistinct()
        return true if user specified to use SQL DISTINCT (effectively excludes id property).
        Specified by:
        isDistinct in interface SpiQuery<T>
      • setCountDistinct

        public DefaultOrmQuery<TsetCountDistinct​(CountDistinctOrder countDistinctOrder)
        Description copied from interface: Query
        Extended version for setDistinct in conjunction with "findSingleAttributeList";
        
        
          List<CountedValue<Order.Status>> orderStatusCount =
        
             DB.find(Order.class)
              .select("status")
              .where()
              .gt("orderDate", LocalDate.now().minusMonths(3))
        
              // fetch as single attribute with a COUNT
              .setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
              .findSingleAttributeList();
        
             for (CountedValue<Order.Status> entry : orderStatusCount) {
               System.out.println(" count:" + entry.getCount()+" orderStatus:" + entry.getValue() );
             }
        
           // produces
        
           count:3 orderStatus:NEW
           count:1 orderStatus:SHIPPED
           count:1 orderStatus:COMPLETE
        
         
        Specified by:
        setCountDistinct in interface Query<T>
      • getInheritType

        public Class<? extends TgetInheritType()
        Description copied from interface: Query
        Returns the inherit type. This is normally the same as getBeanType() returns as long as no other type is set.
        Specified by:
        getInheritType in interface Query<T>
      • setInheritType

        public Query<TsetInheritType​(Class<? extends T> type)
        Description copied from interface: Query
        Restrict the query to only return subtypes of the given inherit type.
        
        
           List<Animal> animals =
             new QAnimal()
               .name.startsWith("Fluffy")
               .setInheritType(Cat.class)
               .findList();
        
         
        Specified by:
        setInheritType in interface Query<T>
        Parameters:
        type - An inheritance subtype of the
      • setFirstRow

        public DefaultOrmQuery<TsetFirstRow​(int firstRow)
        Description copied from interface: Query
        Set the first row to return for this query.
        Specified by:
        setFirstRow in interface Query<T>
        Parameters:
        firstRow - the first row to include in the query result.
      • setMaxRows

        public DefaultOrmQuery<TsetMaxRows​(int maxRows)
        Description copied from interface: Query
        Set the maximum number of rows to return in the query.
        Specified by:
        setMaxRows in interface Query<T>
        Parameters:
        maxRows - the maximum number of rows to return in the query.
      • setMapKey

        public DefaultOrmQuery<TsetMapKey​(String mapKey)
        Description copied from interface: Query
        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 = DB.find(Product.class)
             .setMapKey("sku")  // sku map keys...
             .findMap();
        
         
        Specified by:
        setMapKey in interface Query<T>
        Parameters:
        mapKey - the property to use as keys for a map.
      • getId

        public Object getId()
        Description copied from interface: Query
        Return the Id value.
        Specified by:
        getId in interface Query<T>
      • setId

        public DefaultOrmQuery<TsetId​(Object id)
        Description copied from interface: Query
        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 = DB.find(Order.class)
             .setId(1)
             .fetch("details")
             .findOne();
        
         // the order details were eagerly fetched
         List<OrderDetail> details = order.getDetails();
        
         
        Specified by:
        setId in interface Query<T>
      • where

        public DefaultOrmQuery<Twhere​(Expression expression)
        Description copied from interface: Query
        Add a single Expression to the where clause returning the query.
        
        
         List<Order> newOrders = DB.find(Order.class)
         		.where().eq("status", Order.NEW)
         		.findList();
         ...
        
         
        Specified by:
        where in interface Query<T>
      • text

        public ExpressionList<Ttext()
        Description copied from interface: Query
        Add Full text search expressions for Document store queries.

        This is currently ElasticSearch only and provides the full text expressions such as Match and Multi-Match.

        This automatically makes this query a "Doc Store" query and will execute against the document store (ElasticSearch).

        Expressions added here are added to the "query" section of an ElasticSearch query rather than the "filter" section.

        Expressions added to the where() are added to the "filter" section of an ElasticSearch query.

        Specified by:
        text in interface Query<T>
      • where

        public ExpressionList<Twhere()
        Description copied from interface: Query
        Add Expressions to the where clause with the ability to chain on the ExpressionList. You can use this for adding multiple expressions to the where clause.
        
        
         List<Order> orders = DB.find(Order.class)
             .where()
               .eq("status", Order.NEW)
               .ilike("customer.name","rob%")
             .findList();
        
         
        Specified by:
        where in interface Query<T>
        Returns:
        The ExpressionList for adding expressions to.
        See Also:
        Expr
      • having

        public DefaultOrmQuery<Thaving​(Expression expression)
        Description copied from interface: Query
        Add an expression to the having clause returning the query.

        Currently only beans based on raw sql will use the having clause.

        This is similar to Query.having() except it returns the query rather than the ExpressionList. This is useful when you want to further specify something on the query.

        Specified by:
        having in interface Query<T>
        Parameters:
        expression - the expression to add to the having clause.
        Returns:
        the Query object
      • having

        public ExpressionList<Thaving()
        Description copied from interface: Query
        Add Expressions to the Having clause return the ExpressionList.

        Currently only beans based on raw sql will use the having clause.

        Note that this returns the ExpressionList (so you can add multiple expressions to the query in a fluent API way).

        Specified by:
        having in interface Query<T>
        Returns:
        The ExpressionList for adding more expressions to.
        See Also:
        Expr
      • getGeneratedSql

        public String getGeneratedSql()
        Description copied from interface: Query
        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.

        Specified by:
        getGeneratedSql in interface Query<T>
      • setBufferFetchSizeHint

        public Query<TsetBufferFetchSizeHint​(int bufferFetchSizeHint)
        Description copied from interface: Query
        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.

        Note that internally findEach and findEachWhile will set the fetch size if it has not already as these queries expect to process a lot of rows. If we didn't then Postgres and MySql for example would eagerly pull back all the row data and potentially consume a lot of memory in the process.

        As findEach and findEachWhile automatically set the fetch size we don't have to do so generally but we might still wish to for tuning a specific use case.

        Specified by:
        setBufferFetchSizeHint in interface Query<T>
      • setDisableReadAuditing

        public Query<TsetDisableReadAuditing()
        Description copied from interface: Query
        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.

        Specified by:
        setDisableReadAuditing in interface Query<T>
      • setFutureFetch

        public void setFutureFetch​(boolean backgroundFetch)
        Description copied from interface: SpiQuery
        Set to true to indicate the query is executing in a background thread asynchronously.
        Specified by:
        setFutureFetch in interface SpiQuery<T>
      • setBaseTable

        public Query<TsetBaseTable​(String baseTable)
        Description copied from interface: Query
        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();
        
         
        Specified by:
        setBaseTable in interface Query<T>
      • cancel

        public void cancel()
        Description copied from interface: Query
        Cancel the query execution if supported by the underlying database and driver.

        This must be called from a different thread to the query executor.

        Specified by:
        cancel in interface Query<T>
      • validate

        public Set<Stringvalidate()
        Description copied from interface: Query
        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.

        Specified by:
        validate in interface Query<T>
      • orderById

        public Query<TorderById​(boolean orderById)
        Description copied from interface: Query
        Controls, if paginated queries should always append an 'order by id' statement at the end to guarantee a deterministic sort result. This may affect performance. If this is not enabled, and an orderBy is set on the query, it's up to the programmer that this query provides a deterministic result.
        Specified by:
        orderById in interface Query<T>