Class EntityDao

java.lang.Object
io.github.blyznytsiaorg.bibernate.dao.EntityDao
All Implemented Interfaces:
Dao

public class EntityDao extends Object implements Dao
Data Access Object (DAO) implementation for managing entities in Bibernate.

This DAO provides methods for interacting with the database to perform CRUD operations on entities. It uses a combination of JDBC and custom SQL queries to execute operations such as saving, updating, deleting, and querying entities. The class is designed to be used with various entities and supports flexible querying.

The DAO utilizes the provided SqlBuilder for constructing SQL queries, BibernateDatabaseSettings for obtaining database-related settings, EntityPersistent for entity-related persistence operations, and Identity for managing identity generators.

The class supports logging executed queries, which can be useful for debugging and monitoring database interactions.

Note: This class assumes that entities follow the convention of having an identifier (ID) column, and it supports primary key-based operations accordingly.

Since:
1.0
Author:
Blyzhnytsia Team
  • Field Details

    • sqlBuilder

      private final SqlBuilder sqlBuilder
      The SQL builder used to construct SQL queries.
    • bibernateDatabaseSettings

      private final BibernateDatabaseSettings bibernateDatabaseSettings
      The settings related to the Bibernate database.
    • entityPersistent

      private final EntityPersistent entityPersistent
      Manages the persistence state of entities during database operations.
    • identity

      private final Identity identity
      The identity manager responsible for generating unique identifiers for entities.
    • executedQueries

      private final List<String> executedQueries
      List of executed SQL queries during the session. Provides a record of queries executed.
  • Constructor Details

    • EntityDao

      public EntityDao()
  • Method Details

    • findById

      public <T> Optional<T> findById(Class<T> entityClass, Object primaryKey)
      Retrieves an entity by its primary key. If the result set contains more than one entity, a NonUniqueResultException is thrown.
      Specified by:
      findById in interface Dao
      Type Parameters:
      T - The type of the entity.
      Parameters:
      entityClass - The class of the entity.
      primaryKey - The primary key value to search for.
      Returns:
      An Optional containing the found entity, or an empty Optional if not found.
      Throws:
      NullPointerException - if either entityClass or primaryKey is null.
      NonUniqueResultException - if more than one entity is found for the given primary key.
    • findAll

      public <T> List<T> findAll(Class<T> entityClass)
      Retrieves all entities of a given class from the database.
      Specified by:
      findAll in interface Dao
      Type Parameters:
      T - The type of the entity.
      Parameters:
      entityClass - The class of the entity.
      Returns:
      A list containing all entities of the specified class.
      Throws:
      NullPointerException - if entityClass is null.
      BibernateGeneralException - if an error occurs while executing the query.
    • findAllById

      public <T> List<T> findAllById(Class<T> entityClass, Collection<Object> primaryKeys)
      Retrieves entities by their primary keys from the database.
      Specified by:
      findAllById in interface Dao
      Type Parameters:
      T - The type of the entity.
      Parameters:
      entityClass - The class of the entity.
      primaryKeys - The collection of primary key values to search for.
      Returns:
      A list containing the found entities.
      Throws:
      NullPointerException - if entityClass or primaryKeys is null.
      BibernateGeneralException - if an error occurs while executing the query.
    • findAllByColumnValue

      public <T> List<T> findAllByColumnValue(Class<T> entityClass, String columnName, Object columnValue)
      Retrieves a list of entities of type T based on the specified column's value.

      This method constructs a WHERE condition using the provided column name and value and delegates to findByWhere(Class, String, Object...) method for execution.

      Specified by:
      findAllByColumnValue in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      columnName - The name of the column.
      columnValue - The value to match in the specified column.
      Returns:
      A list of entities matching the specified column value.
    • findByWhere

      public <T> List<T> findByWhere(Class<T> entityClass, String whereCondition, Object... bindValues)
      Retrieves a list of entities of type T based on the specified WHERE condition.

      This method constructs a SELECT query using the provided entity class, WHERE condition, and optional bind values, and delegates to findByQuery(Class, String, Object...) method for execution.

      If the entity has any one-to-one eager fetch type relationships, it utilizes a left join for fetching.

      Specified by:
      findByWhere in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      whereCondition - The WHERE condition for the query.
      bindValues - The optional bind values for the WHERE condition.
      Returns:
      A list of entities matching the specified WHERE condition.
    • findByJoinTableField

      public <T> List<T> findByJoinTableField(Class<T> entityClass, Field field, Object... bindValues)
      Retrieves a list of entities of type T based on the specified field and optional bind values.

      This method constructs a SELECT query using the provided entity class, field, and optional bind values, and delegates to findByQuery(Class, String, Object...) method for execution.

      If the entity has any one-to-one eager fetch type relationships, it utilizes a left join for fetching.

      Specified by:
      findByJoinTableField in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      field - The field for the join operation.
      bindValues - The optional bind values for the join operation.
      Returns:
      A list of entities matching the specified join table field.
    • findByWhereJoin

      public <T> List<T> findByWhereJoin(Class<T> entityClass, Object... bindValues)
      Retrieves a list of entities of type T using a left join for fetching, based on the specified entity class and optional bind values.
      Specified by:
      findByWhereJoin in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      bindValues - The optional bind values for the left join operation.
      Returns:
      A list of entities matching the specified left join operation.
    • findAllByWhereJoin

      public <T> List<T> findAllByWhereJoin(Class<T> entityClass, String query, Object... bindValues)
      Retrieves a list of entities of type T using a left join for fetching, based on the specified entity class, query, and optional bind values.
      Specified by:
      findAllByWhereJoin in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      query - The query for the left join operation.
      bindValues - The optional bind values for the left join operation.
      Returns:
      A list of entities matching the specified left join operation.
    • findByQuery

      public <T> List<T> findByQuery(Class<T> entityClass, String query, Object... bindValues)
      Retrieves a list of entities of type T based on the provided SQL query and optional bind values.

      This method prepares a SQL query, executes it, and maps the result set to entities of type T.

      Specified by:
      findByQuery in interface Dao
      Type Parameters:
      T - The type of entities to retrieve.
      Parameters:
      entityClass - The class of the entity.
      query - The SQL query to execute.
      bindValues - The optional bind values for the query.
      Returns:
      A list of entities based on the specified SQL query.
    • find

      public int find(String query, Object[] bindValues)
      Executes a SQL query and retrieves an integer result.
      Specified by:
      find in interface Dao
      Parameters:
      query - The SQL query to execute.
      bindValues - The bind values for the query.
      Returns:
      The integer result obtained from the executed SQL query.
    • update

      public <T> void update(Class<T> entityClass, Object entity, List<ColumnSnapshot> diff)
      Updates an entity of type T in the database based on the provided differences.

      This method prepares and executes an SQL update query and handles version checking if a version column is present.

      Specified by:
      update in interface Dao
      Type Parameters:
      T - The type of entity to update.
      Parameters:
      entityClass - The class of the entity.
      entity - The entity to update.
      diff - The list of differences between the current and original entity state.
    • save

      public <T> T save(Class<T> entityClass, T entity)
      Saves an entity of type T in the database.

      This method sets the version value if null, saves the entity using the identity, generates sql query for insert using different id generators.

      Specified by:
      save in interface Dao
      Type Parameters:
      T - The type of entity to save.
      Parameters:
      entityClass - The class of the entity.
      entity - The entity to save.
      Returns:
      The saved entity.
    • saveAll

      public <T> void saveAll(Class<T> entityClass, Collection<T> entities)
      Saves a collection of entities of type T in the database.

      This method sets the version value if null, saves the collection using the identity, generates sql query for insert using different id generators.

      Specified by:
      saveAll in interface Dao
      Type Parameters:
      T - The type of entities to save.
      Parameters:
      entityClass - The class of the entities.
      entities - The collection of entities to save.
    • deleteById

      public <T> void deleteById(Class<T> entityClass, Object primaryKey)
      Deletes an entity of type T by its primary key.
      Specified by:
      deleteById in interface Dao
      Type Parameters:
      T - The type of entity to delete.
      Parameters:
      entityClass - The class of the entity.
      primaryKey - The primary key of the entity to delete.
    • deleteByColumnValue

      public <T> List<T> deleteByColumnValue(Class<T> entityClass, String columnName, Object value)
      Deletes entities of type T based on a specified column value.
      Specified by:
      deleteByColumnValue in interface Dao
      Type Parameters:
      T - The type of entities to delete.
      Parameters:
      entityClass - The class of the entities.
      columnName - The name of the column to use for deletion.
      value - The value of the column to match for deletion.
      Returns:
      A list of deleted entities.
    • deleteAllById

      public <T> void deleteAllById(Class<T> entityClass, Collection<Object> primaryKeys)
      Deletes entities of type T by their primary keys.
      Specified by:
      deleteAllById in interface Dao
      Type Parameters:
      T - The type of entities to delete.
      Parameters:
      entityClass - The class of the entities.
      primaryKeys - The collection of primary keys for entities to delete.
    • delete

      public <T> void delete(Class<T> entityClass, Object entity)
      Deletes an entity of type T by providing the entity instance.
      Specified by:
      delete in interface Dao
      Type Parameters:
      T - The type of entity to delete.
      Parameters:
      entityClass - The class of the entity.
      entity - The entity instance to delete.
    • deleteAll

      public <T> void deleteAll(Class<T> entityClass, Collection<T> entities)
      Deletes all entities of type T from the database based on the provided collection of entities.

      This method takes a collection of entities, determines their primary keys and version values (if applicable), and executes batch delete queries to remove the entities from the database.

      Specified by:
      deleteAll in interface Dao
      Type Parameters:
      T - The type of entities to delete.
      Parameters:
      entityClass - The class of the entities.
      entities - The collection of entities to delete.
    • startTransaction

      public void startTransaction() throws SQLException
      Starts a new transaction and put it into ThreadLocal. If transaction is already in ThreadLocal will be kept the same.
      Specified by:
      startTransaction in interface Dao
      Throws:
      SQLException - If an SQL exception occurs while starting the transaction.
    • commitTransaction

      public void commitTransaction() throws SQLException
      Commits the current transaction.
      Specified by:
      commitTransaction in interface Dao
      Throws:
      SQLException - If an SQL exception occurs while committing the transaction.
    • rollbackTransaction

      public void rollbackTransaction() throws SQLException
      Rolls back the current transaction.
      Specified by:
      rollbackTransaction in interface Dao
      Throws:
      SQLException - If an SQL exception occurs while rolling back the transaction.
    • createLeftJoinQuery

      private <T> String createLeftJoinQuery(Class<T> entityClass)
    • deleteByColumnValue

      private <T> List<T> deleteByColumnValue(Class<T> entityClass, String columnName, Object value, boolean returnDeletedEntities)
    • getTransaction

      private Transaction getTransaction() throws SQLException
      Throws:
      SQLException
    • removeToManyRelations

      private <T> void removeToManyRelations(Class<T> entityClass, Object value, BibernateSession session, List<EntityColumnDetails> relationsForRemoval)
    • removeToOneRelations

      private <T> void removeToOneRelations(List<T> deletedEntities, BibernateSession session, List<EntityColumnDetails> relationsForRemoval)
    • preparePrimaryKeyToVersionValues

      private <T> List<org.flywaydb.core.internal.util.Pair<Object,Object>> preparePrimaryKeyToVersionValues(Class<T> entityClass, Collection<T> entities, boolean isVersionFound)
    • prepareQuery

      private <T> String prepareQuery(Class<T> entityClass, boolean isVersionFound, String tableName, String fieldIdName, List<org.flywaydb.core.internal.util.Pair<Object,Object>> primaryKeyToVersionValues, List<Object> primaryKeys)
    • addToExecutedQueries

      private void addToExecutedQueries(String query)
    • showSql

      private void showSql(Runnable logSql)
    • populatePreparedStatement

      private void populatePreparedStatement(Object[] bindValues, PreparedStatement statement) throws SQLException
      Throws:
      SQLException
    • populatePreparedStatement

      private void populatePreparedStatement(Object entity, PreparedStatement statement, String fieldIdName, Object fieldIdValue, Number fieldVersionValue, List<ColumnSnapshot> diff) throws SQLException
      Throws:
      SQLException
    • isIdField

      private boolean isIdField(String fieldIdName, Field field)
    • isUpdateTimestamp

      private boolean isUpdateTimestamp(Field field)
    • throwErrorMessage

      private void throwErrorMessage(String errorMessage, Exception exe)
    • hasAnyOneToOneEagerFetchType

      private boolean hasAnyOneToOneEagerFetchType(EntityMetadata entityMetadata)