Class DefaultServer

    • Method Detail

      • executePlugins

        public void executePlugins​(boolean online)
        Execute all the plugins with an online flag indicating the DB is up or not.
      • script

        public ScriptRunner script()
        Description copied from interface: Database
        Return a ScriptRunner for running SQL or DDL scripts.

        Intended to use mostly in testing to run seed SQL scripts or truncate table scripts etc.

        Specified by:
        script in interface Database
      • initialise

        public void initialise()
        Run any initialisation required before registering with the ClusterManager.
      • start

        public void start()
        Start any services after registering with the ClusterManager.
      • shutdown

        public void shutdown​(boolean shutdownDataSource,
                             boolean deregisterDriver)
        Shutting down manually.
        Specified by:
        shutdown in interface Database
        Parameters:
        shutdownDataSource - if true then shutdown the underlying DataSource if it is the Ebean DataSource implementation.
        deregisterDriver - if true then deregister the JDBC driver if it is the Ebean DataSource implementation.
      • extended

        public ExtendedServer extended()
        Description copied from interface: Database
        Return the extended API for Database.

        The extended API has the options for executing queries that take an explicit transaction as an argument.

        Typically we only need to use the extended API when we do NOT want to use the usual ThreadLocal based mechanism to obtain the current transaction but instead supply the transaction explicitly.

        Specified by:
        extended in interface Database
      • setClock

        public void setClock​(Clock clock)
        Description copied from interface: ExtendedServer
        Set the Clock to use for @WhenCreated and @WhenModified.

        Note that we only expect to change the Clock for testing purposes.

        Specified by:
        setClock in interface ExtendedServer
      • refreshMany

        public void refreshMany​(Object parentBean,
                                String propertyName)
        Description copied from interface: Database
        Refresh a many property of an entity bean.
        Specified by:
        refreshMany in interface Database
        Parameters:
        parentBean - the entity bean containing the 'many' property
        propertyName - the 'many' property to be refreshed
      • refresh

        public void refresh​(Object bean)
        Description copied from interface: Database
        Refresh the values of a bean.

        Note that this resets OneToMany and ManyToMany properties so that if they are accessed a lazy load will refresh the many property.

        Specified by:
        refresh in interface Database
      • diff

        public Map<String,​ValuePairdiff​(Object a,
                                                Object b)
        Description copied from interface: Database
        Return a map of the differences between two objects of the same type.

        When null is passed in for b, then the 'OldValues' of a is used for the difference comparison.

        Specified by:
        diff in interface Database
      • externalModification

        public void externalModification​(TransactionEventTable tableEvent)
        Process committed beans from another framework or server in another cluster.

        This notifies this instance of the framework that beans have been committed externally to it. Either by another framework or clustered server. It needs to maintain its cache and text indexes appropriately.

        Specified by:
        externalModification in interface SpiEbeanServer
      • externalModification

        public void externalModification​(String tableName,
                                         boolean inserts,
                                         boolean updates,
                                         boolean deletes)
        Developer informing eBean that tables where modified outside of eBean. Invalidate the cache etc as required.
        Specified by:
        externalModification in interface Database
        Parameters:
        tableName - the name of the table that was modified
        inserts - true if rows where inserted into the table
        updates - true if rows on the table where updated
        deletes - true if rows on the table where deleted
      • truncate

        public void truncate​(Class<?>... types)
        Description copied from interface: Database
        Truncate the base tables for the given bean types.
        Specified by:
        truncate in interface Database
      • createEntityBean

        public <T> T createEntityBean​(Class<T> type)
        Create a new EntityBean bean.

        This will generally return a subclass of the parameter 'type' which additionally implements the EntityBean interface. That is, the returned bean is typically an instance of a dynamically generated class.

        Specified by:
        createEntityBean in interface Database
      • getReference

        public <T> T getReference​(Class<T> type,
                                  Object id)
        Return a Reference bean.

        If a current transaction is active then this will check the Context of that transaction to see if the bean is already loaded. If it is already loaded then it will returned that object.

        Specified by:
        getReference in interface Database
        Parameters:
        type - the type of entity bean
        id - the id value
      • register

        public void register​(TransactionCallback transactionCallback)
        Description copied from interface: Database
        Register a TransactionCallback on the currently active transaction.

        If there is no currently active transaction then a PersistenceException is thrown.

        Specified by:
        register in interface Database
        Parameters:
        transactionCallback - The transaction callback to be registered with the current transaction.
      • createTransaction

        public Transaction createTransaction​(io.ebean.annotation.TxIsolation isolation)
        Create a transaction additionally specify the Isolation level.

        Note that this transaction is not stored in a thread local.

        Specified by:
        createTransaction in interface Database
      • executeCall

        public <T> T executeCall​(Callable<T> c)
        Description copied from interface: Database
        Execute a TxCallable in a Transaction with the default scope.

        The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).

        
        
           database.executeCall(new Callable<String>() {
             public String call() {
               User u1 = database.find(User.class, 1);
               User u2 = database.find(User.class, 2);
        
               u1.setName("u1 mod");
               u2.setName("u2 mod");
        
               database.save(u1);
               database.save(u2);
        
               return u1.getEmail();
             }
           });
        
         
        Specified by:
        executeCall in interface Database
      • executeCall

        public <T> T executeCall​(TxScope scope,
                                 Callable<T> c)
        Description copied from interface: Database
        Execute a TxCallable in a Transaction with an explicit scope.

        The scope can control the transaction type, isolation and rollback semantics.

        
        
           // set specific transactional scope settings
           TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
        
           database.executeCall(scope, new Callable<String>() {
         	   public String call() {
         		   User u1 = database.find(User.class, 1);
         		   ...
         		   return u1.getEmail();
             }
           });
        
         
        Specified by:
        executeCall in interface Database
      • execute

        public void execute​(Runnable r)
        Description copied from interface: Database
        Execute a Runnable in a Transaction with the default scope.

        The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).

        
        
            database.execute(() -> {
        
                User u1 = database.find(User.class, 1);
                User u2 = database.find(User.class, 2);
        
                u1.setName("u1 mod");
                u2.setName("u2 mod");
        
                u1.save();
                u2.save();
            });
        
         
        Specified by:
        execute in interface Database
      • execute

        public void execute​(TxScope scope,
                            Runnable r)
        Description copied from interface: Database
        Execute a Runnable in a Transaction with an explicit scope.

        The scope can control the transaction type, isolation and rollback semantics.

        
        
           // set specific transactional scope settings
           TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
        
           database.execute(scope, new Runnable() {
         	   public void run() {
         		   User u1 = database.find(User.class, 1);
         		   ...
             }
           });
        
         
        Specified by:
        execute in interface Database
      • beginTransaction

        public Transaction beginTransaction()
        Description copied from interface: Database
        Start a transaction with 'REQUIRED' semantics.

        With REQUIRED semantics if an active transaction already exists that transaction will be used.

        The transaction is stored in a ThreadLocal variable and typically you only need to use the returned Transaction IF you wish to do things like use batch mode, change the transaction isolation level, use savepoints or log comments to the transaction log.

        Example of using a transaction to span multiple calls to find(), save() etc.

        Using try with resources

        
        
            // start a transaction (stored in a ThreadLocal)
        
            try (Transaction txn = database.beginTransaction()) {
        
         	    Order order = database.find(Order.class, 10);
         	    ...
         	    database.save(order);
        
         	    txn.commit();
            }
        
         

        Using try finally block

        
        
            // start a transaction (stored in a ThreadLocal)
            Transaction txn = database.beginTransaction();
            try {
         	    Order order = database.find(Order.class,10);
        
         	    database.save(order);
        
         	    txn.commit();
        
            } finally {
         	    txn.end();
            }
        
         

        Transaction options

        
        
             try (Transaction txn = database.beginTransaction()) {
        
               // explicitly turn on/off JDBC batch use
               txn.setBatchMode(true);
               txn.setBatchSize(50);
        
               // control flushing when mixing save and queries
               txn.setBatchFlushOnQuery(false);
        
               // turn off persist cascade if needed
               txn.setPersistCascade(false);
        
               // for large batch insert processing when we do not
               // ... need the generatedKeys, don't get them
               txn.setBatchGetGeneratedKeys(false);
        
               // explicitly flush the JDBC batch buffer
               txn.flush();
        
               ...
        
               txn.commit();
            }
        
         

        If you want to externalise the transaction management then you use createTransaction() and pass the transaction around to the various methods on Database yourself.

        Specified by:
        beginTransaction in interface Database
      • beginTransaction

        public Transaction beginTransaction​(TxScope txScope)
        Description copied from interface: Database
        Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.

        Note that this provides an try finally alternative to using Database.executeCall(TxScope, Callable) or Database.execute(TxScope, Runnable).

        REQUIRES_NEW example:

        
         // Start a new transaction. If there is a current transaction
         // suspend it until this transaction ends
         try (Transaction txn = database.beginTransaction(TxScope.requiresNew())) {
        
           ...
        
           // commit the transaction
           txn.commit();
        
           // At end this transaction will:
           //  A) will rollback transaction if it has not been committed
           //  B) will restore a previously suspended transaction
         }
        
         

        REQUIRED example:

        
        
         // start a new transaction if there is not a current transaction
         try (Transaction txn = database.beginTransaction(TxScope.required())) {
        
           ...
        
           // commit the transaction if it was created or
           // do nothing if there was already a current transaction
           txn.commit();
         }
        
         
        Specified by:
        beginTransaction in interface Database
      • flush

        public void flush()
        Description copied from interface: Database
        Flush the JDBC batch on the current transaction.

        This only is useful when JDBC batch is used. Flush occurs automatically when the transaction commits or batch size is reached. This manually flushes the JDBC batch buffer.

        This is the same as currentTransaction().flush().

        Specified by:
        flush in interface Database
      • endTransaction

        public void endTransaction()
        Description copied from interface: Database
        If the current transaction has already been committed do nothing otherwise rollback the transaction.

        Useful to put in a finally block to ensure the transaction is ended, rather than a rollbackTransaction() in each catch block.

        Code example:

        
        
           database.beginTransaction();
           try {
             // do some fetching and or persisting ...
        
             // commit at the end
             database.commitTransaction();
        
           } finally {
             // if commit didn't occur then rollback the transaction
             database.endTransaction();
           }
        
         
        Specified by:
        endTransaction in interface Database
      • nextId

        public Object nextId​(Class<?> beanType)
        Description copied from interface: Database
        Return the next unique identity value for a given bean type.

        This will only work when a IdGenerator is on the bean such as for beans that use a DB sequence or UUID.

        For DB's supporting getGeneratedKeys and sequences such as Oracle10 you do not need to use this method generally. It is made available for more complex cases where it is useful to get an ID prior to some processing.

        Specified by:
        nextId in interface Database
      • sort

        public <T> void sort​(List<T> list,
                             String sortByClause)
        Description copied from interface: Database
        Sort the list in memory using the sortByClause which can contain a comma delimited list of property names and keywords asc, desc, nullsHigh and nullsLow.
        • asc - ascending order (which is the default)
        • desc - Descending order
        • nullsHigh - Treat null values as high/large values (which is the default)
        • nullsLow- Treat null values as low/very small values

        If you leave off any keywords the defaults are ascending order and treating nulls as high values.

        Note that the sorting uses a Comparator and Collections.sort(); and does not invoke a DB query.

        
        
           // find orders and their customers
           List<Order> list = database.find(Order.class)
             .fetch("customer")
             .order("id")
             .findList();
        
           // sort by customer name ascending, then by order shipDate
           // ... then by the order status descending
           database.sort(list, "customer.name, shipDate, status desc");
        
           // sort by customer name descending (with nulls low)
           // ... then by the order id
           database.sort(list, "customer.name desc nullsLow, id");
        
         
        Specified by:
        sort in interface Database
        Parameters:
        list - the list of entity beans
        sortByClause - the properties to sort the list by
      • validateQuery

        public <T> Set<StringvalidateQuery​(Query<T> query)
        Description copied from interface: Database
        Returns the set of properties/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/path for the given bean type.

        Specified by:
        validateQuery in interface Database
      • filter

        public <T> Filter<T> filter​(Class<T> beanType)
        Description copied from interface: Database
        Create a filter for sorting and filtering lists of entities locally without going back to the database.

        This produces and returns a new list with the sort and filters applied.

        Refer to Filter for an example of its use.

        Specified by:
        filter in interface Database
      • update

        public <T> UpdateQuery<T> update​(Class<T> beanType)
        Description copied from interface: Database
        Create an Update query to perform a bulk update.

        
        
          int rows = database
              .update(Customer.class)
              .set("status", Customer.Status.ACTIVE)
              .set("updtime", new Timestamp(System.currentTimeMillis()))
              .where()
                .gt("id", 1000)
                .update();
        
         
        Specified by:
        update in interface Database
        Type Parameters:
        T - The type of entity bean
        Parameters:
        beanType - The type of entity bean to update
        Returns:
        The update query to use
      • merge

        public void merge​(Object bean)
        Description copied from interface: Database
        Merge the bean using the default merge options (no paths specified, default delete).
        Specified by:
        merge in interface Database
        Parameters:
        bean - The bean to merge
      • merge

        public void merge​(Object bean,
                          MergeOptions options)
        Description copied from interface: Database
        Merge the bean using the given merge options.
        Specified by:
        merge in interface Database
        Parameters:
        bean - The bean to merge
        options - The options to control the merge
      • merge

        public void merge​(Object bean,
                          MergeOptions options,
                          Transaction transaction)
        Description copied from interface: Database
        Merge the bean using the given merge options and a transaction.
        Specified by:
        merge in interface Database
        Parameters:
        bean - The bean to merge
        options - The options to control the merge
      • find

        public <T> Query<T> find​(Class<T> beanType)
        Description copied from interface: Database
        Create a query for a type of entity bean.

        You can use the methods on the Query object to specify fetch paths, predicates, order by, limits etc.

        You then use findList(), findSet(), findMap() and findOne() to execute the query and return the collection or bean.

        Note that a query executed by Query.findList() Query.findSet() etc will execute against the same Database from which is was created.

        
        
           // Find order 2 specifying explicitly the parts of the object graph to
           // eagerly fetch. In this case eagerly fetch the associated customer,
           // details and details.product.name
        
           Order order = database.find(Order.class)
             .fetch("customer")
             .fetch("details")
             .fetch("detail.product", "name")
             .setId(2)
             .findOne();
        
           // find some new orders ... with firstRow/maxRows
           List<Order> orders =
             database.find(Order.class)
               .where().eq("status", Order.Status.NEW)
               .setFirstRow(20)
               .setMaxRows(10)
               .findList();
        
         
        Specified by:
        find in interface Database
      • findNative

        public <T> Query<T> findNative​(Class<T> beanType,
                                       String nativeSql)
        Description copied from interface: Database
        Create a query using native SQL.

        The native SQL can contain named parameters or positioned parameters.

        
        
           String sql = "select c.id, c.name from customer c where c.name like ? order by c.name";
        
           Query<Customer> query = database.findNative(Customer.class, sql);
           query.setParameter(1, "Rob%");
        
           List<Customer> customers = query.findList();
        
         
        Specified by:
        findNative in interface Database
        Parameters:
        beanType - The type of entity bean to fetch
        nativeSql - The SQL that can contain named or positioned parameters
        Returns:
        The query to set parameters and execute
      • createNamedQuery

        public <T> Query<T> createNamedQuery​(Class<T> beanType,
                                             String namedQuery)
        Description copied from interface: Database
        Create a named query.

        For RawSql the named query is expected to be in ebean.xml.

        Specified by:
        createNamedQuery in interface Database
        Type Parameters:
        T - The type of entity bean
        Parameters:
        beanType - The type of entity bean
        namedQuery - The name of the query
        Returns:
        The query
      • createQuery

        public <T> DefaultOrmQuery<T> createQuery​(Class<T> beanType,
                                                  String eql)
        Description copied from interface: Database
        Parse the Ebean query language statement returning the query which can then be modified (add expressions, change order by clause, change maxRows, change fetch and select paths etc).

        Example

        
        
           // Find order additionally fetching the customer, details and details.product name.
        
           String ormQuery = "fetch customer fetch details fetch details.product (name) where id = :orderId ";
        
           Query<Order> query = DB.createQuery(Order.class, ormQuery);
           query.setParameter("orderId", 2);
        
           Order order = query.findOne();
        
           // This is the same as:
        
           Order order = DB.find(Order.class)
             .fetch("customer")
             .fetch("details")
             .fetch("detail.product", "name")
             .setId(2)
             .findOne();
        
         
        Specified by:
        createQuery in interface Database
        Type Parameters:
        T - The type of the entity bean
        Parameters:
        beanType - The type of bean to fetch
        eql - The Ebean ORM query
        Returns:
        The query with expressions defined as per the parsed query statement
      • createUpdate

        public <T> Update<T> createUpdate​(Class<T> beanType,
                                          String ormUpdate)
        Description copied from interface: Database
        Create a orm update where you will supply the insert/update or delete statement (rather than using a named one that is already defined using the @NamedUpdates annotation).

        The orm update differs from the sql update in that it you can use the bean name and bean property names rather than table and column names.

        An example:

        
        
           // The bean name and properties - "topic","postCount" and "id"
        
           // will be converted into their associated table and column names
           String updStatement = "update topic set postCount = :pc where id = :id";
        
           Update<Topic> update = database.createUpdate(Topic.class, updStatement);
        
           update.set("pc", 9);
           update.set("id", 3);
        
           int rows = update.execute();
           System.out.println("rows updated:" + rows);
        
         
        Specified by:
        createUpdate in interface Database
      • findDto

        public <T> DtoQuery<T> findDto​(Class<T> dtoType,
                                       String sql)
        Description copied from interface: Database
        Create a Query for DTO beans.

        DTO beans are just normal bean like classes with public constructor(s) and setters. They do not need to be registered with DB before use.

        Specified by:
        findDto in interface Database
        Type Parameters:
        T - The type of the DTO bean.
        Parameters:
        dtoType - The type of the DTO bean the rows will be mapped into.
        sql - The SQL query to execute.
      • createNamedDtoQuery

        public <T> DtoQuery<T> createNamedDtoQuery​(Class<T> dtoType,
                                                   String namedQuery)
        Description copied from interface: Database
        Create a named Query for DTO beans.

        DTO beans are just normal bean like classes with public constructor(s) and setters. They do not need to be registered with DB before use.

        Specified by:
        createNamedDtoQuery in interface Database
        Type Parameters:
        T - The type of the DTO bean.
        Parameters:
        dtoType - The type of the DTO bean the rows will be mapped into.
        namedQuery - The name of the query
      • sqlUpdate

        public SqlUpdate sqlUpdate​(String sql)
        Description copied from interface: Database
        Look to execute a native sql insert update or delete statement.

        Use this to execute a Insert Update or Delete statement. The statement will be native to the database and contain database table and column names.

        See SqlUpdate for example usage.

        Specified by:
        sqlUpdate in interface Database
        Returns:
        The SqlUpdate instance to set parameters and execute
      • find

        public <T> T find​(Class<T> beanType,
                          Object uid)
        Description copied from interface: Database
        Find a bean using its unique id.

        
           // Fetch order 1
           Order order = database.find(Order.class, 1);
         

        If you want more control over the query then you can use createQuery() and Query.findOne();

        
           // ... additionally fetching customer, customer shipping address,
           // order details, and the product associated with each order detail.
           // note: only product id and name is fetch (its a "partial object").
           // note: all other objects use "*" and have all their properties fetched.
        
           Query<Order> query = database.find(Order.class)
             .setId(1)
             .fetch("customer")
             .fetch("customer.shippingAddress")
             .fetch("details")
             .query();
        
           // fetch associated products but only fetch their product id and name
           query.fetch("details.product", "name");
        
        
           Order order = query.findOne();
        
           // traverse the object graph...
        
           Customer customer = order.getCustomer();
           Address shippingAddress = customer.getShippingAddress();
           List<OrderDetail> details = order.getDetails();
           OrderDetail detail0 = details.get(0);
           Product product = detail0.getProduct();
           String productName = product.getName();
        
         
        Specified by:
        find in interface Database
        Parameters:
        beanType - the type of entity bean to fetch
        uid - the id value
      • find

        public <T> T find​(Class<T> beanType,
                          Object id,
                          Transaction t)
        Find a bean using its unique id.
        Specified by:
        find in interface Database
        Type Parameters:
        T - the type of entity bean to find
        Parameters:
        beanType - the type of entity bean to find
        id - the bean id value
        t - the transaction to use (can be null)
      • findOne

        public <T> T findOne​(Query<T> query,
                             Transaction transaction)
        Description copied from interface: ExtendedServer
        Execute the query returning at most one entity bean or null (if no matching bean is found).

        This will throw a NonUniqueResultException if the query finds more than one result.

        Generally you are able to use Query.findOne() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        Specified by:
        findOne in interface ExtendedServer
        Type Parameters:
        T - the type of entity bean to fetch.
        Parameters:
        query - the query to execute.
        transaction - the transaction to use (can be null).
        Returns:
        the list of fetched beans.
        See Also:
        Query.findOne()
      • findSet

        public <T> Set<T> findSet​(Query<T> query,
                                  Transaction t)
        Description copied from interface: ExtendedServer
        Execute the query returning a set of entity beans.

        Generally you are able to use Query.findSet() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        
        
         Set<Customer> customers = DB.find(Customer.class)
             .where().ilike("name", "rob%")
             .findSet();
        
         
        Specified by:
        findSet in interface ExtendedServer
        Type Parameters:
        T - the type of entity bean to fetch.
        Parameters:
        query - the query to execute
        t - the transaction to use (can be null).
        Returns:
        the set of fetched beans.
        See Also:
        Query.findSet()
      • findMap

        public <K,​T> Map<K,​T> findMap​(Query<T> query,
                                                  Transaction t)
        Description copied from interface: ExtendedServer
        Execute the query returning the entity beans in a Map.

        Generally you are able to use Query.findMap() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        Specified by:
        findMap in interface ExtendedServer
        T - the type of entity bean to fetch.
        Parameters:
        query - the query to execute.
        t - the transaction to use (can be null).
        Returns:
        the map of fetched beans.
        See Also:
        Query.findMap()
      • findSingleAttributeList

        public <A,​T> List<A> findSingleAttributeList​(Query<T> query,
                                                           Transaction t)
        Description copied from interface: ExtendedServer
        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 ExtendedServer
        Returns:
        the list of values for the selected property
        See Also:
        Query.findSingleAttributeList()
      • exists

        public <T> boolean exists​(Query<?> ormQuery,
                                  Transaction transaction)
        Description copied from interface: ExtendedServer
        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:

        
        
           boolean userExists = query().where().eq("email", "[email protected]").exists();
        
         

        Example using a query bean:

        
        
           boolean userExists = new QContact().email.equalTo("[email protected]").exists();
        
         
        Specified by:
        exists in interface ExtendedServer
        Returns:
        True if the query finds a matching row in the database
      • findIdsWithCopy

        public <A,​T> List<A> findIdsWithCopy​(Query<T> query,
                                                   Transaction t)
        Description copied from interface: SpiEbeanServer
        Execute the findId's query but without copying the query.

        Used so that the list of Id's can be made accessible to client code before the query has finished (if executing in a background thread).

        Specified by:
        findIdsWithCopy in interface SpiEbeanServer
      • delete

        public <T> int delete​(Query<T> query,
                              Transaction t)
        Description copied from interface: ExtendedServer
        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 ExtendedServer
        Type Parameters:
        T - the type of entity bean to fetch.
        Parameters:
        query - the query used for the delete
        t - the transaction to use (can be null)
        Returns:
        the number of beans/rows that were deleted
      • update

        public <T> int update​(Query<T> query,
                              Transaction t)
        Description copied from interface: ExtendedServer
        Execute the update query returning the number of rows updated.

        The update query must be created using Database.update(Class).

        Specified by:
        update in interface ExtendedServer
        Type Parameters:
        T - the type of entity bean
        Parameters:
        query - the update query to execute
        t - the optional transaction to use for the update (can be null)
        Returns:
        The number of rows updated
      • findFutureCount

        public <T> FutureRowCount<T> findFutureCount​(Query<T> q,
                                                     Transaction t)
        Description copied from interface: ExtendedServer
        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 ExtendedServer
        Parameters:
        q - the query to execute the row count on
        t - the transaction (can be null).
        Returns:
        a Future object for the row count query
        See Also:
        Query.findFutureCount()
      • findFutureIds

        public <T> FutureIds<T> findFutureIds​(Query<T> query,
                                              Transaction t)
        Description copied from interface: ExtendedServer
        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 ExtendedServer
        Parameters:
        query - the query to execute the fetch Id's on
        t - the transaction (can be null).
        Returns:
        a Future object for the list of Id's
        See Also:
        Query.findFutureIds()
      • findFutureList

        public <T> FutureList<T> findFutureList​(Query<T> query,
                                                Transaction t)
        Description copied from interface: ExtendedServer
        Execute find list query in a background thread returning a FutureList object.

        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).

        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 ExtendedServer
        Parameters:
        query - the query to execute in the background
        t - the transaction (can be null).
        Returns:
        a Future object for the list result of the query
        See Also:
        Query.findFutureList()
      • findPagedList

        public <T> PagedList<T> findPagedList​(Query<T> query,
                                              Transaction transaction)
        Description copied from interface: ExtendedServer
        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 ExtendedServer
        Returns:
        The PagedList
        See Also:
        Query.findPagedList()
      • findEach

        public <T> void findEach​(Query<T> query,
                                 Consumer<T> consumer,
                                 Transaction t)
        Description copied from interface: ExtendedServer
        Execute the query visiting the each bean one at a time.

        Unlike findList() this is suitable for processing a query that will return a very large resultSet. The reason is that not all the result beans need to be held in memory at the same time and instead processed one at a time.

        Internally this query using a PersistenceContext scoped to each bean (and the beans associated object graph).

        
        
             DB.find(Order.class)
               .where().eq("status", Order.Status.NEW)
               .order().asc("id")
               .findEach((Order order) -> {
        
                 // do something with the order bean
                 System.out.println(" -- processing order ... " + order);
               });
        
         
        Specified by:
        findEach in interface ExtendedServer
        See Also:
        Query.findEach(Consumer), Query.findEachWhile(Predicate)
      • findEachWhile

        public <T> void findEachWhile​(Query<T> query,
                                      Predicate<T> consumer,
                                      Transaction t)
        Description copied from interface: ExtendedServer
        Execute the query visiting the each bean one at a time.

        Compared to findEach() this provides the ability to stop processing the query results early by returning false for the Predicate.

        Unlike findList() this is suitable for processing a query that will return a very large resultSet. The reason is that not all the result beans need to be held in memory at the same time and instead processed one at a time.

        Internally this query using a PersistenceContext scoped to each bean (and the beans associated object graph).

        
        
             DB.find(Order.class)
               .where().eq("status", Order.Status.NEW)
               .order().asc("id")
               .findEachWhile((Order order) -> {
        
                 // do something with the order bean
                 System.out.println(" -- processing order ... " + order);
        
                 boolean carryOnProcessing = ...
                 return carryOnProcessing;
               });
        
         
        Specified by:
        findEachWhile in interface ExtendedServer
        See Also:
        Query.findEach(Consumer), Query.findEachWhile(Predicate)
      • findVersions

        public <T> List<Version<T>> findVersions​(Query<T> query,
                                                 Transaction transaction)
        Description copied from interface: ExtendedServer
        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.

        Specified by:
        findVersions in interface ExtendedServer
      • findList

        public <T> List<T> findList​(Query<T> query,
                                    Transaction t)
        Description copied from interface: ExtendedServer
        Execute a query returning a list of beans.

        Generally you are able to use Query.findList() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        
        
         List<Customer> customers = DB.find(Customer.class)
             .where().ilike("name", "rob%")
             .findList();
        
         
        Specified by:
        findList in interface ExtendedServer
        Type Parameters:
        T - the type of entity bean to fetch.
        Parameters:
        query - the query to execute.
        t - the transaction to use (can be null).
        Returns:
        the list of fetched beans.
        See Also:
        Query.findList()
      • findOne

        public SqlRow findOne​(SqlQuery query,
                              Transaction t)
        Description copied from interface: ExtendedServer
        Execute the sql query returning a single MapBean or null.

        This will throw a PersistenceException if the query found more than one result.

        Generally you are able to use SqlQuery.findOne() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        Specified by:
        findOne in interface ExtendedServer
        Parameters:
        query - the query to execute.
        t - the transaction to use (can be null).
        Returns:
        the fetched MapBean or null if none was found.
        See Also:
        SqlQuery.findOne()
      • findEachWhile

        public void findEachWhile​(SqlQuery query,
                                  Predicate<SqlRow> consumer,
                                  Transaction transaction)
        Description copied from interface: ExtendedServer
        Execute the SqlQuery iterating a row at a time with the ability to stop consuming part way through.

        Returning false after processing a row stops the iteration through the query results.

        This streaming type query is useful for large query execution as only 1 row needs to be held in memory.

        Specified by:
        findEachWhile in interface ExtendedServer
      • findList

        public List<SqlRowfindList​(SqlQuery query,
                                     Transaction t)
        Description copied from interface: ExtendedServer
        Execute the sql query returning a list of MapBean.

        Generally you are able to use SqlQuery.findList() rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.

        Specified by:
        findList in interface ExtendedServer
        Parameters:
        query - the query to execute.
        t - the transaction to use (can be null).
        Returns:
        the list of fetched MapBean.
        See Also:
        SqlQuery.findList()
      • save

        public void save​(Object bean)
        Persist the bean by either performing an insert or update.
        Specified by:
        save in interface Database
      • markAsDirty

        public void markAsDirty​(Object bean)
        Description copied from interface: Database
        Marks the entity bean as dirty.

        This is used so that when a bean that is otherwise unmodified is updated the version property is updated.

        An unmodified bean that is saved or updated is normally skipped and this marks the bean as dirty so that it is not skipped.

        
        
         Customer customer = database.find(Customer, id);
        
         // mark the bean as dirty so that a save() or update() will
         // increment the version property
         database.markAsDirty(customer);
         database.save(customer);
        
         
        Specified by:
        markAsDirty in interface Database
      • update

        public void update​(Object bean)
        Description copied from interface: Database
        Saves the bean using an update. If you know you are updating a bean then it is preferable to use this update() method rather than save().

        Stateless updates: Note that the bean does not have to be previously fetched to call update().You can create a new instance and set some of its properties programmatically for via JSON/XML marshalling etc. This is described as a 'stateless update'.

        Optimistic Locking: Note that if the version property is not set when update() is called then no optimistic locking is performed (internally ConcurrencyMode.NONE is used).

        
        
         // A 'stateless update' example
         Customer customer = new Customer();
         customer.setId(7);
         customer.setName("ModifiedNameNoOCC");
         database.update(customer);
        
         
        Specified by:
        update in interface Database
      • updateAll

        public void updateAll​(Collection<?> beans)
                       throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Update a collection of beans. If there is no current transaction one is created and used to update all the beans in the collection.
        Specified by:
        updateAll in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • publish

        public <T> List<T> publish​(Query<T> query,
                                   Transaction transaction)
        Description copied from interface: Database
        Publish the beans that match the query returning the resulting published beans.

        The values are published from the draft beans to the live beans.

        Specified by:
        publish in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        query - the query used to select the draft beans to publish
        transaction - the transaction the publish process should use (can be null)
      • publish

        public <T> T publish​(Class<T> beanType,
                             Object id)
        Description copied from interface: Database
        Publish a single bean given its type and id returning the resulting live bean. This will use the current transaction or create one if required.

        The values are published from the draft to the live bean.

        Specified by:
        publish in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        beanType - the type of the entity bean
        id - the id of the entity bean
      • publish

        public <T> List<T> publish​(Query<T> query)
        Description copied from interface: Database
        Publish the beans that match the query returning the resulting published beans. This will use the current transaction or create one if required.

        The values are published from the draft beans to the live beans.

        Specified by:
        publish in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        query - the query used to select the draft beans to publish
      • publish

        public <T> T publish​(Class<T> beanType,
                             Object id,
                             Transaction transaction)
        Description copied from interface: Database
        Publish a single bean given its type and id returning the resulting live bean.

        The values are published from the draft to the live bean.

        Specified by:
        publish in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        beanType - the type of the entity bean
        id - the id of the entity bean
        transaction - the transaction the publish process should use (can be null)
      • draftRestore

        public <T> List<T> draftRestore​(Query<T> query,
                                        Transaction transaction)
        Description copied from interface: Database
        Restore the draft beans matching the query back to the live state.

        The values from the live beans are set back to the draft bean and the @DraftDirty and @DraftReset properties are reset.

        Specified by:
        draftRestore in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        query - the query used to select the draft beans to restore
        transaction - the transaction the restore process should use (can be null)
      • draftRestore

        public <T> T draftRestore​(Class<T> beanType,
                                  Object id,
                                  Transaction transaction)
        Description copied from interface: Database
        Restore the draft bean back to the live state.

        The values from the live beans are set back to the draft bean and the @DraftDirty and @DraftReset properties are reset.

        Specified by:
        draftRestore in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        beanType - the type of the entity bean
        id - the id of the entity bean to restore
        transaction - the transaction the restore process should use (can be null)
      • draftRestore

        public <T> T draftRestore​(Class<T> beanType,
                                  Object id)
        Description copied from interface: Database
        Restore the draft bean back to the live state.

        The values from the live beans are set back to the draft bean and the @DraftDirty and @DraftReset properties are reset.

        Specified by:
        draftRestore in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        beanType - the type of the entity bean
        id - the id of the entity bean to restore
      • draftRestore

        public <T> List<T> draftRestore​(Query<T> query)
        Description copied from interface: Database
        Restore the draft beans matching the query back to the live state.

        The values from the live beans are set back to the draft bean and the @DraftDirty and @DraftReset properties are reset.

        Specified by:
        draftRestore in interface Database
        Type Parameters:
        T - the type of the entity bean
        Parameters:
        query - the query used to select the draft beans to restore
      • saveAll

        public int saveAll​(Collection<?> beans,
                           Transaction transaction)
                    throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Save all the beans in the collection with an explicit transaction.
        Specified by:
        saveAll in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • saveAll

        public int saveAll​(Collection<?> beans)
                    throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Save all the beans in the collection.
        Specified by:
        saveAll in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • saveAll

        public int saveAll​(Object... beans)
                    throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Save all the beans.
        Specified by:
        saveAll in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • delete

        public boolean delete​(Object bean,
                              Transaction t)
                       throws javax.persistence.OptimisticLockException
        Delete the bean with the explicit transaction.
        Specified by:
        delete in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • deletePermanent

        public boolean deletePermanent​(Object bean)
                                throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Delete a bean permanently without soft delete.
        Specified by:
        deletePermanent in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • deletePermanent

        public boolean deletePermanent​(Object bean,
                                       Transaction t)
                                throws javax.persistence.OptimisticLockException
        Description copied from interface: Database
        Delete a bean permanently without soft delete using an explicit transaction.
        Specified by:
        deletePermanent in interface Database
        Throws:
        javax.persistence.OptimisticLockException
      • execute

        public int execute​(SqlUpdate updSql)
        Execute the updateSql.
        Specified by:
        execute in interface Database
        Parameters:
        updSql - the update sql potentially with bind values
        Returns:
        the number of rows updated or deleted. -1 if executed in batch.
        See Also:
        CallableSql
      • setBeanId

        public Object setBeanId​(Object bean,
                                Object id)
        Description copied from interface: Database
        Set the Id value onto the bean converting the type of the id value if necessary.

        For example, if the id value passed in is a String but ought to be a Long or UUID etc then it will automatically be converted.

        Specified by:
        setBeanId in interface Database
        Parameters:
        bean - The entity bean to set the id value on.
        id - The id value to set.
      • json

        public JsonContext json()
        Description copied from interface: Database
        Return the JsonContext for reading/writing JSON.

        This instance is safe to be used concurrently by multiple threads and this method is cheap to call.

        Simple example:

        
        
             JsonContext json = database.json();
             String jsonOutput = json.toJson(list);
             System.out.println(jsonOutput);
        
         

        Using PathProperties:

        
        
             // specify just the properties we want
             PathProperties paths = PathProperties.parse("name, status, anniversary");
        
             List<Customer> customers =
               database.find(Customer.class)
                 // apply those paths to the query (only fetch what we need)
                 .apply(paths)
                 .where().ilike("name", "rob%")
                 .findList();
        
             // ... get the json
             JsonContext jsonContext = database.json();
             String json = jsonContext.toJson(customers, paths);
        
         
        Specified by:
        json in interface Database
        See Also:
        FetchPath, Query.apply(FetchPath)
      • checkUniqueness

        public Set<PropertycheckUniqueness​(Object bean)
        Description copied from interface: Database
        This method checks the uniqueness of a bean. I.e. if the save will work. It will return the properties that violates an unique / primary key. This may be done in an UI save action to validate if the user has entered correct values.

        Note: This method queries the DB for uniqueness of all indices, so do not use it in a batch update.

        Note: This checks only the root bean!

        
        
           // there is a unique constraint on title
        
           Document doc = new Document();
           doc.setTitle("One flew over the cuckoo's nest");
           doc.setBody("clashes with doc1");
        
           Set<Property> properties = DB.checkUniqueness(doc);
        
           if (properties.isEmpty()) {
             // it is unique ... carry on
        
           } else {
             // build a user friendly message
             // to return message back to user
        
             String uniqueProperties = properties.toString();
        
             StringBuilder msg = new StringBuilder();
        
             properties.forEach((it)-> {
               Object propertyValue = it.getVal(doc);
               String propertyName = it.getName();
               msg.append(" property["+propertyName+"] value["+propertyValue+"]");
             });
        
             // uniqueProperties > [title]
             //       custom msg > property[title] value[One flew over the cuckoo's nest]
        
          }
        
         
        Specified by:
        checkUniqueness in interface Database
        Parameters:
        bean - The entity bean to check uniqueness on
        Returns:
        a set of Properties if constraint validation was detected or empty list.