Class DbControl

java.lang.Object
net.sf.basedb.core.DbControl
All Implemented Interfaces:
AutoCloseable

public final class DbControl
extends Object
implements AutoCloseable
A DbControl object is the main object used for communicating with the database. It contains methods for saving and deleting items, handling transactions, etc. DbControl objects are created by the SessionControl.newDbControl() method.
Version:
2.0
Author:
Nicklas, Samuel
Last modified
$Date: 2021-05-07 13:44:50 +0200 (Fri, 07 May 2021) $
  • Field Details

    • log

      private static final org.slf4j.Logger log
      Log core events.
    • sc

      private final SessionControl sc
    • name

      private final String name
      The name of this transaction.
      Since:
      3.19
    • state

      private final DbControl.State state
      The state is holding Hibernate database connections and transaction.
    • logControl

      private LogControl logControl
      Handles logging of changes to items.
    • logInterceptor

      private LoggingInterceptor logInterceptor
    • pspManager

    • itemCache

      private Map<BasicData,​BasicItem> itemCache
      A cache of already loaded items. Maps from data object --> item object
    • commitQueue

      private Map<BasicItem,​Transactional.Action> commitQueue
      A list of items that need special handling when commit is called.
    • saveIfQueue

      private Map<BasicItem,​List<DbControl.SaveIf>> saveIfQueue
      Lists items that are saved only if the parent item is also saved.
      See Also:
      saveItemIf(BasicItem, BasicItem, boolean)
    • batchers

      private List<Batcher> batchers
      A list of batchers that will be closed when DbControl is closed and will be flushed when commit is called.
    • transactionalActions

      private List<TransactionalAction> transactionalActions
      List of actions that should be performed when the transaction commits or rollbacks.
    • isClosed

      private boolean isClosed
      Is the connection closed or not?
    • isRolledBack

      private boolean isRolledBack
      If the current transaction has been rolled back or not.
    • uniqueRandoms

      private Set<String> uniqueRandoms
      Holds random strings that must be unique within a transaction.
  • Constructor Details

  • Method Details

    • isClosed

      public boolean isClosed()
      Check if the connection to the database has been closed. To get a new connection, you must create a new DbControl object.
      Returns:
      TRUE if the connection is closed, FALSE otherwise
      See Also:
      SessionControl.newDbControl()
    • getSessionControl

      public SessionControl getSessionControl()
      Get the SessionControl object that owns this DbControl object.
      Returns:
      a SessionControl object
    • getName

      public String getName()
      Get the name of this transaction.
      Since:
      3.19
    • getLogControl

      LogControl getLogControl()
      Get the log controller for this db control. May be null if logging has been disabled.
      Since:
      2.13
    • getProjectSpecificAnnotationsManager

      ProjectSpecificAnnotationsManager getProjectSpecificAnnotationsManager()
      Get the manager used for handling project specific annotations in this transaction.
    • getLoggingInterceptor

      LoggingInterceptor getLoggingInterceptor()
      Get the logging interceptor for this db control. Can be used to add changes not intercepted by Hibernate (eg. after executing SQL directly against the database).
      Returns:
      Can be null if logging is disabled
      Since:
      3.3
    • getHibernateSession

      Session getHibernateSession()
      Get the underlying Hibernate session.
    • getStatelessSession

      StatelessSession getStatelessSession()
      Get a stateless Hibernate session using the same database connection as the regular session. If no stateless session exists a new one is created.
    • disconnect

      @Deprecated public void disconnect() throws ConnectionClosedException, BaseException
      Deprecated.
      In 3.12. Applications should use separate DbControl instead.
      Temporarily disconnect from the database. Uncommitted changes of regular items are not lost, but you must reconnect() before calling commit(). If you have used batch items, for example ReporterBatcher, you should call commit() or you will lose everything that has already been BasicBatcher.flush():ed to the database.
      Throws:
      ConnectionClosedException - If connection to database has been closed.
      BaseException - If there is another error
    • reconnect

      @Deprecated public void reconnect() throws ConnectionClosedException, BaseException
      Deprecated.
      In 3.12. Applications should use separate DbControl instead.
      Reconnects to the database after a disconnect().
      Throws:
      ConnectionClosedException - If connection to database has been closed.
      BaseException - If there is another error.
    • isConnected

      @Deprecated public boolean isConnected()
      Deprecated.
      In 3.11. Applications should use separate DbControl instead.
      Checks if there is an active connection to the database or not.
    • close

      public void close()
      Close the connection to the database. Uncommitted changes will be rolled back. If the connection is already closed this method does nothing. Any errors in this method are written to the log file. After calling this method the DbControl cannot be used anymore.
      Specified by:
      close in interface AutoCloseable
    • isRolledBack

      public boolean isRolledBack()
      If the transaction was rolled back, either as a call to close() or because of an error during commit(). To check if a transaction was successfully committed use: dc.isClosed() && !dc.isRolledBack().
      Returns:
      TRUE if the transaction was rolled back, FALSE if it was committed or is still open
    • rollback

      private void rollback()
      Rollback the transaction.
    • cleanUp

      private void cleanUp()
      Clear and close all objects.
    • addTransactionalAction

      public void addTransactionalAction​(TransactionalAction action)
      Add a transactional action to this DbControl.
      Since:
      3.1
    • commit

      public void commit() throws BaseException
      Commit all changes made to items and close the connection to the database. If there is an error, a rollback is issued and the connection is closed.
      Throws:
      BaseException - If there is an error
    • updateDiskUsage

      private void updateDiskUsage​(BasicItem item) throws QuotaException, BaseException
      Update the disk usage information for a DiskConsumable item. It is expected that the item parameter impements the DiskConsumable interface and that it's data object implements the DiskConsumableData interface.
      Throws:
      QuotaException - If the quota is exceeded
      BaseException - If there is another error
    • getDiskUsage

      long getDiskUsage​(UserData user, QuotaTypeData quotaType, Location location) throws BaseException
      Get the disk usage for the specified user at the specified location and quota type.
      Throws:
      BaseException
    • getDiskUsage

      long getDiskUsage​(GroupData group, QuotaTypeData quotaType, Location location) throws BaseException
      Get the disk usage for the specified group at the specified location and quota type.
      Throws:
      BaseException
    • newItem

      <I extends BasicItem> I newItem​(Class<I> itemClass, Object... extraParameters)
      Create a new item.
      Parameters:
      itemClass - The class of the item
      Returns:
      An object of the itemClass class
      Throws:
      BaseException - If there is an error
    • logEntry

      public void logEntry​(ManualLogEntry logEntry)
      Add a manual log entry to the history log. If logging is disabled this call is ignored.
      Since:
      3.9
    • loadItem

      public <I extends BasicItem> I loadItem​(I item)
      Load an item from the database. If the item is already attached to this DbControl the same instance is returned, otherwise a new instance is created an attached to this DbControl.
      Parameters:
      item - The item to load
      Returns:
      An item that is attached to this DbControl (or null if item is null)
      Since:
      3.1
    • loadItem

      <I extends BasicItem> I loadItem​(Class<I> itemClass, int id) throws PermissionDeniedException, BaseException
      Load an item from the database when you now the id. If the item has already been loaded the item in the cache will be used.
      Parameters:
      itemClass - The Class of the item object
      id - The id of the object
      Returns:
      An object of the itemClass class
      Throws:
      PermissionDeniedException - If the logged in user doesn't have read permission
      BaseException - If there is another error
    • loadItemByDataClass

      <I extends BasicItem,​ D extends BasicData> I loadItemByDataClass​(Class<I> itemClass, Class<D> dataClass, int id) throws PermissionDeniedException, BaseException
      Load an item from the database when you know the id. If the item has already been loaded the item in the cache will be used.
      Parameters:
      itemClass - The item class for the object
      dataClass - The actual data class for the object which must be compatible with the item class
      id - The id of the object
      Returns:
      An object of the itemClass class
      Throws:
      PermissionDeniedException
      BaseException
      Since:
      2.17
    • getItem

      <I extends BasicItem> I getItem​(Class<I> itemClass, BasicData data, Object... extraParameters) throws PermissionDeniedException, ItemNotFoundException, BaseException
      Get an item object for a known data object, using the cache if possible. If the item already exists in the cache that object is returned, otherwise a new item object is created assuming that a constructor that takes a single data object as parameter exists.
      Parameters:
      itemClass - The Class of the item object
      data - The data object, or null
      Returns:
      An object of the itemClass class, or null if null was passed
      Throws:
      PermissionDeniedException - If the logged in user doesn't have read permission
      ItemNotFoundException - If the data object is a Hibernate proxy which points to a non-existing row in the database
      BaseException - If there is another error
    • saveItem

      Schedule a new item to be saved in the database. The item is saved the next time the commit() method is called.
      Parameters:
      item - The item to be saved
      Throws:
      PermissionDeniedException - If the logged in user doesn't have create permission
      ItemAlreadyExistsException - If the item already exists in the database
      BaseException - If there is another error
    • saveItemIf

      public void saveItemIf​(BasicItem itemIf, BasicItem item, boolean before)
      Schedule a new item to be saved in the database if another item is also saved. If the itemIf item is saved then item is also saved, otherwise it is not. The method is useful for utility methods that creates a lot of child items to a parent item and we wan't to wait putting them in the real save queue until the parent item is saved. If the parent item is already in the database or saveItem(itemIf) has been called this method is the same as saveItem(item)
      Parameters:
      itemIf - The parent item that must be saved
      item - The item to save when the parent item is saved
      before - TRUE if the item should be saved before the itemIf, FALSE to save itemIf first
      See Also:
      saveItem(BasicItem)
    • deleteItem

      public void deleteItem​(BasicItem item) throws PermissionDeniedException, ItemNotFoundException, BaseException
      Schedule an existing item to be deleted from the database. The item is deleted the next time the commit() method is called. If you are deleting multiple items it is better to use Trashcan.delete(SessionControl, java.util.Collection, boolean, ProgressReporter) since it will automatically select the best order to delete the items.
      Parameters:
      item - The item to be deleted
      Throws:
      PermissionDeniedException - If the logged in user doesn't have delete permission
      ItemNotFoundException - If the item doesn't exist in the database
      BaseException - If there is another error
    • detachItem

      public void detachItem​(BasicItem item) throws BaseException
      Detach an item from this DbControl. The detached item will no longer be managed and changes will not be saved to the database. For some items, certain operations are forbidden for detached items. For example you are not allowed to upload files to File items.
      Parameters:
      item - The item to be detached
      Throws:
      BaseException - If there is an error
      See Also:
      reattachItem(BasicItem, boolean)
    • reattachItem

      public <T extends BasicItem> T reattachItem​(T item, boolean updated) throws PermissionDeniedException, ItemNotFoundException, BaseException
      Reattach a detached item from this DbControl. If the reattached already exists in the database it will be managed and changes will be saved to the database.
      Parameters:
      item - The item to be reattached
      updated - If TRUE, the item has been updated while it was detached and changes will be saved to the database. If FALSE, the item will only be saved to the database if it is modified after the reattachement
      Returns:
      The reattached item
      Throws:
      PermissionDeniedException - If the logged in user doesn't have read/write permission
      BaseException - If there is another error
      ItemNotFoundException
      Since:
      2.13
      See Also:
      detachItem(BasicItem)
    • refreshItem

      public void refreshItem​(BasicItem item)
      Reload the item from the database. If the item isn't attached to this DbControl it is automatically reattached first.
      Parameters:
      item - The item to reload
      Since:
      2.4
    • isAttached

      boolean isAttached​(BasicItem item)
      Check if an item is attached to this DbControl. An item is attached if it is found in either the item cache (existing items only) or commit queue (new or existing items).
    • initCollection

      public void initCollection​(BasicItem item, String collectionName) throws BaseException
      Initialise a collection on an item. This method is useful if you detach an item but needs to use a collection while it is detached. Since collections are not loaded until they are needed, you will get an exception if you try to access an unitialised collection of a detached item. One example is if you have detach a Quota object and calls the Quota.getQuotaValue(QuotaType, Location) method.
      Parameters:
      item - The item
      collectionName - The name of the collection
      Throws:
      BaseException - If there is an error
      See Also:
      detachItem(BasicItem), reattachItem(BasicItem, boolean)
    • uniqueRandom

      public String uniqueRandom()
      Generate a random string value that is unique for the given transaction.
      Since:
      3.4
    • addBatcher

      void addBatcher​(Batcher batcher)
      Add a Batcher to the batcher queue.
      Parameters:
      batcher - The Batcher to add
    • removeBatcher

      void removeBatcher​(Batcher batcher)
      Remove a Batcher from the batcher queue.
      Parameters:
      batcher - The Batcher to remove
    • createTempIdTable

      public String createTempIdTable​(Set<Integer> idList)
      Create a temporary table for holding given list of ID values. The intention is that this should be used in a query to speed up the execution. Note that not all databases may support this feature and that alternate solutions are needed. The temporary table is automatically deleted when the transaction ends.
      Parameters:
      idList - List of ID values that should be inserted
      Returns:
      The name of the temporary table or null if not supported
      Since:
      3.18