Class Database


  • public class Database
    extends java.lang.Object
    Database link for subsequent CRUD operations
    • Constructor Summary

      Constructors 
      Constructor Description
      Database​(DatabaseConnectionFactory connectionFactory)
      Create a database via custom connection factory
      Database​(java.lang.String jndiName)
      Create database object via JNDI handle
      Database​(java.lang.String driverName, java.lang.String jdbcUrl, java.lang.String username, java.lang.String password)
      Create database with simple non-pooled connections
      Database​(javax.sql.DataSource dataSource)
      Create database object via datasource
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected void authorize​(java.lang.Object entity)
      Override this method to authorize an entity before saving it to database
      <T> java.util.List<T> bulkInsert​(java.util.List<T> entities)
      Insert a collection of entities into database as a batch.
      void delete​(java.lang.Class<?> entityClass, java.lang.Object id)
      Delete an existing record
      int deleteWhere​(java.lang.Class<?> entityClass, java.lang.String whereExpression, java.lang.Object... whereParameters)
      Delete multiple records
      <T> T getById​(java.lang.Class<? extends T> entityClass, java.lang.Object id)
      Fetch a single record/entity from a database table
      Dialect getDialect()  
      java.lang.String getSchema()  
      protected java.lang.String injectIntoWhereExpression​(java.lang.Class<?> entityClass, java.lang.String whereExpression)
      Override this method to manipulate SQL WHERE expression for database SELECT, UPDATE and DELETE statements.
      protected java.lang.Object[] injectWhereParameters​(java.lang.Class<?> entityClass, java.lang.Object[] whereParameters)
      Override this method to manipulate SQL WHERE parameters for database SELECT, UPDATE and DELETE statements.
      <T> T insert​(T entity)
      Insert a single entity into database
      <T> java.util.List<T> listAll​(java.lang.Class<? extends T> entityClass)
      Fetch all records/entities from a database table into a list
      <T> java.util.List<T> listWhere​(java.lang.Class<? extends T> entityClass, java.lang.String whereExpression, java.lang.Object... whereParameters)
      Fetch records from the entity-related table and return records in list
      Database setBatchSize​(int size)
      Modify the default batch size in bulk insert
      Database setLogger​(java.util.function.Consumer<java.lang.String> logger)  
      Database setSchema​(java.lang.String schema)  
      SqlQuery sql​(java.lang.String sqlSelect, java.lang.Object... whereParameters)
      Prepare a SELECT query
      <T> java.util.stream.Stream<? extends T> streamWhere​(java.lang.Class<? extends T> entityClass, java.lang.String whereExpression, java.lang.Object... whereParameters)
      Fetch records from the entity-related table and return records in stream
      <T> T transaction​(TransactionStatements<T> statements)
      Runs a bunch of statements in a single transaction
      void update​(java.lang.Object entity)
      Update an existing entity in database.
      SqlQuery where​(java.lang.String whereExpression, java.lang.Object... whereParameters)
      Prepare a SELECT query with WHERE filter only.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • Database

        public Database​(javax.sql.DataSource dataSource)
        Create database object via datasource
        Parameters:
        dataSource - data source, which provides database connections
      • Database

        public Database​(DatabaseConnectionFactory connectionFactory)
        Create a database via custom connection factory
        Parameters:
        connectionFactory - custom connection factory, which provides database connections
      • Database

        public Database​(java.lang.String jndiName)
                 throws javax.naming.NamingException
        Create database object via JNDI handle
        Parameters:
        jndiName - JNDI name, for example "jdbc/demoDB"
        Throws:
        javax.naming.NamingException - when JNDI name lookup fails
      • Database

        public Database​(java.lang.String driverName,
                        java.lang.String jdbcUrl,
                        java.lang.String username,
                        java.lang.String password)
                 throws java.lang.Exception
        Create database with simple non-pooled connections
        Parameters:
        driverName - driver class name, for example "org.postgresql.Driver"
        jdbcUrl - database URL, for example "jdbc:postgresql://localhost:5432/demoDB"
        username - SQL username
        password - SQL password
        Throws:
        java.lang.Exception - when anything goes wrong
    • Method Detail

      • setBatchSize

        public Database setBatchSize​(int size)
        Modify the default batch size in bulk insert
        Parameters:
        size - batch size
        Returns:
        database object
      • insert

        public <T> T insert​(T entity)
                     throws BindException,
                            java.sql.SQLException,
                            UnauthorizedException
        Insert a single entity into database
        Type Parameters:
        T - entity type
        Parameters:
        entity - entity to insert
        Returns:
        the same entity, with @Id field (if any) being initialized
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
        UnauthorizedException - when entity saving is unauthorized (in authorize-method)
      • bulkInsert

        public <T> java.util.List<T> bulkInsert​(java.util.List<T> entities)
                                         throws BindException,
                                                java.sql.SQLException,
                                                UnauthorizedException
        Insert a collection of entities into database as a batch. Batch insertion is faster than inserting one by one.
        Type Parameters:
        T - entity type
        Parameters:
        entities - collection of entities to insert
        Returns:
        the same entities, with @Id field (if any) being initialized
        Throws:
        java.sql.SQLException - when an SQL specific error occurs (see method setBatchSize() in case of large entity lists)
        BindException - when data binding fails
        UnauthorizedException - when entity saving is unauthorized (in authorize-method)
      • update

        public void update​(java.lang.Object entity)
                    throws BindException,
                           java.sql.SQLException,
                           RecordNotFoundException,
                           UnauthorizedException
        Update an existing entity in database. Only entities with @Id field can be updated. When @Id field is missing, use method update(entity, whereExpression, whereParameters)
        Parameters:
        entity - entity with new attribute values
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
        RecordNotFoundException - when referenced entity was not found in database
        UnauthorizedException - when entity saving is unauthorized (in authorize-method)
      • delete

        public void delete​(java.lang.Class<?> entityClass,
                           java.lang.Object id)
                    throws BindException,
                           java.sql.SQLException,
                           RecordNotFoundException
        Delete an existing record
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        id - entity id
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
        RecordNotFoundException - when referenced entity was not found in database
      • deleteWhere

        public int deleteWhere​(java.lang.Class<?> entityClass,
                               java.lang.String whereExpression,
                               java.lang.Object... whereParameters)
                        throws BindException,
                               java.sql.SQLException
        Delete multiple records
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        whereExpression - SQL WHERE expression, for example "name LIKE ?"
        whereParameters - parameters for WHERE expression
        Returns:
        number of records deleted
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • sql

        public SqlQuery sql​(java.lang.String sqlSelect,
                            java.lang.Object... whereParameters)
                     throws BindException,
                            java.sql.SQLException
        Prepare a SELECT query
        Parameters:
        sqlSelect - SQL SELECT statement
        whereParameters - parameter values for WHERE expression
        Returns:
        query object for fetching the results
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • where

        public SqlQuery where​(java.lang.String whereExpression,
                              java.lang.Object... whereParameters)
                       throws BindException,
                              java.sql.SQLException
        Prepare a SELECT query with WHERE filter only. Subsequent fetch operation (get or list) determines database table for this query
        Parameters:
        whereExpression - SQL WHERE expression, for example "name LIKE ?"
        whereParameters - parameter values for WHERE expression
        Returns:
        query object for fetching the results
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • listWhere

        public <T> java.util.List<T> listWhere​(java.lang.Class<? extends T> entityClass,
                                               java.lang.String whereExpression,
                                               java.lang.Object... whereParameters)
                                        throws BindException,
                                               java.sql.SQLException
        Fetch records from the entity-related table and return records in list
        Type Parameters:
        T - entity type
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        whereExpression - SQL WHERE expression, for example "name LIKE ?"
        whereParameters - parameter values for WHERE expression
        Returns:
        results in list
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • streamWhere

        public <T> java.util.stream.Stream<? extends T> streamWhere​(java.lang.Class<? extends T> entityClass,
                                                                    java.lang.String whereExpression,
                                                                    java.lang.Object... whereParameters)
                                                             throws BindException,
                                                                    java.sql.SQLException
        Fetch records from the entity-related table and return records in stream
        Type Parameters:
        T - entity type
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        whereExpression - SQL WHERE expression, for example "name LIKE ?"
        whereParameters - parameter values for WHERE expression
        Returns:
        results in stream
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • listAll

        public <T> java.util.List<T> listAll​(java.lang.Class<? extends T> entityClass)
                                      throws BindException,
                                             java.sql.SQLException
        Fetch all records/entities from a database table into a list
        Type Parameters:
        T - entity type
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        Returns:
        list of entities
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
      • getById

        public <T> T getById​(java.lang.Class<? extends T> entityClass,
                             java.lang.Object id)
                      throws BindException,
                             java.sql.SQLException,
                             RecordNotFoundException
        Fetch a single record/entity from a database table
        Type Parameters:
        T - entity type
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        id - entity id
        Returns:
        entity; returns null, if id refers to non-existing record
        Throws:
        java.sql.SQLException - when an SQL specific error occurs
        BindException - when data binding fails
        RecordNotFoundException - when referenced entity was not found in database
      • injectIntoWhereExpression

        protected java.lang.String injectIntoWhereExpression​(java.lang.Class<?> entityClass,
                                                             java.lang.String whereExpression)
        Override this method to manipulate SQL WHERE expression for database SELECT, UPDATE and DELETE statements.
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        whereExpression - SQL WHERE expression, for example "name LIKE ?"
        Returns:
        where expression including injections
      • injectWhereParameters

        protected java.lang.Object[] injectWhereParameters​(java.lang.Class<?> entityClass,
                                                           java.lang.Object[] whereParameters)
        Override this method to manipulate SQL WHERE parameters for database SELECT, UPDATE and DELETE statements.
        Parameters:
        entityClass - entity class, which indirectly refers to a database table
        whereParameters - original WHERE parameters
        Returns:
        where WHERE parameters with injections
      • authorize

        protected void authorize​(java.lang.Object entity)
                          throws UnauthorizedException
        Override this method to authorize an entity before saving it to database
        Parameters:
        entity - entity to authorize
        Throws:
        UnauthorizedException - when trying to save unauthorized entity
      • transaction

        public <T> T transaction​(TransactionStatements<T> statements)
                          throws java.sql.SQLException,
                                 TransactionException
        Runs a bunch of statements in a single transaction
        Type Parameters:
        T - entity type
        Parameters:
        statements - statements to run
        Returns:
        the return value from statements
        Throws:
        java.sql.SQLException - when connection allocation, release, commit or rollback fails
        TransactionException - when a exception is thrown inside transaction logic
      • getDialect

        public Dialect getDialect()
      • getSchema

        public java.lang.String getSchema()
      • setSchema

        public Database setSchema​(java.lang.String schema)
      • setLogger

        public Database setLogger​(java.util.function.Consumer<java.lang.String> logger)