Package net.sf.basedb.core
Class DbControl
java.lang.Object
net.sf.basedb.core.DbControl
- All Implemented Interfaces:
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) $
-
Nested Class Summary
Modifier and TypeClassDescriptionprivate static class
(package private) static class
Main purpose is to write a warning to the log file in case some user code that created a DbControl instance never called the close() method before the DbControl became uncreachable. -
Field Summary
Modifier and TypeFieldDescriptionA list of batchers that will be closed whenDbControl
is closed and will be flushed when commit is called.private Map<BasicItem,
Transactional.Action> A list of items that need special handling when commit is called.private boolean
Is the connection closed or not?private boolean
If the current transaction has been rolled back or not.A cache of already loaded items.private static final Logger
Log core events.private LogControl
Handles logging of changes to items.private LoggingInterceptor
private final String
The name of this transaction.private Map<BasicItem,
List<DbControl.SaveIf>> Lists items that are saved only if the parent item is also saved.private final SessionControl
private final DbControl.State
The state is holding Hibernate database connections and transaction.private List<TransactionalAction>
List of actions that should be performed when the transaction commits or rollbacks.Holds random strings that must be unique within a transaction. -
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescription(package private) void
addBatcher
(Batcher batcher) Add aBatcher
to the batcher queue.void
Add a transactional action to this DbControl.private void
cleanUp()
Clear and close all objects.void
close()
Close the connection to the database.void
commit()
Commit all changes made to items and close the connection to the database.createTempIdTable
(Set<Integer> idList) Create a temporary table for holding given list of ID values.void
deleteItem
(BasicItem item) Schedule an existing item to be deleted from the database.void
detachItem
(BasicItem item) Detach an item from thisDbControl
.void
Deprecated.In 3.12.(package private) long
getDiskUsage
(GroupData group, QuotaTypeData quotaType, Location location) Get the disk usage for the specified group at the specified location and quota type.(package private) long
getDiskUsage
(UserData user, QuotaTypeData quotaType, Location location) Get the disk usage for the specified user at the specified location and quota type.(package private) Session
Get the underlying Hibernate session.(package private) <I extends BasicItem>
IGet an item object for a known data object, using the cache if possible.(package private) LogControl
Get the log controller for this db control.(package private) LoggingInterceptor
Get the logging interceptor for this db control.getName()
Get the name of this transaction.(package private) ProjectSpecificAnnotationsManager
Get the manager used for handling project specific annotations in this transaction.Get theSessionControl
object that owns thisDbControl
object.(package private) StatelessSession
Get a stateless Hibernate session using the same database connection as the regular session.void
initCollection
(BasicItem item, String collectionName) Initialise a collection on an item.(package private) boolean
isAttached
(BasicItem item) Check if an item is attached to thisDbControl
.boolean
isClosed()
Check if the connection to the database has been closed.boolean
Deprecated.In 3.11.boolean
<I extends BasicItem>
IloadItem
(I item) Load an item from the database.(package private) <I extends BasicItem>
ILoad an item from the database when you now the id.loadItemByDataClass
(Class<I> itemClass, Class<D> dataClass, int id) Load an item from the database when you know the id.void
logEntry
(ManualLogEntry logEntry) Add a manual log entry to the history log.(package private) <I extends BasicItem>
ICreate a new item.<T extends BasicItem>
TreattachItem
(T item, boolean updated) Reattach a detached item from thisDbControl
.void
Deprecated.In 3.12.void
refreshItem
(BasicItem item) Reload the item from the database.(package private) void
removeBatcher
(Batcher batcher) Remove aBatcher
from the batcher queue.private void
rollback()
Rollback the transaction.void
Schedule a new item to be saved in the database.void
saveItemIf
(BasicItem itemIf, BasicItem item, boolean before) Schedule a new item to be saved in the database if another item is also saved.Generate a random string value that is unique for the given transaction.private void
updateDiskUsage
(BasicItem item) Update the disk usage information for a DiskConsumable item.
-
Field Details
-
log
Log core events. -
sc
-
name
The name of this transaction.- Since:
- 3.19
-
state
The state is holding Hibernate database connections and transaction. -
logControl
Handles logging of changes to items. -
logInterceptor
-
pspManager
-
itemCache
A cache of already loaded items. Maps from data object --> item object -
commitQueue
A list of items that need special handling when commit is called. -
saveIfQueue
Lists items that are saved only if the parent item is also saved. -
batchers
A list of batchers that will be closed whenDbControl
is closed and will be flushed when commit is called. -
transactionalActions
List of actions that should be performed when the transaction commits or rollbacks. -
isClosed
private boolean isClosedIs the connection closed or not? -
isRolledBack
private boolean isRolledBackIf the current transaction has been rolled back or not. -
uniqueRandoms
Holds random strings that must be unique within a transaction.
-
-
Constructor Details
-
DbControl
DbControl(SessionControl sc, String name) throws BaseException Create a new object.- Throws:
BaseException
-
-
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 newDbControl
object.- Returns:
- TRUE if the connection is closed, FALSE otherwise
- See Also:
-
getSessionControl
Get theSessionControl
object that owns thisDbControl
object.- Returns:
- a
SessionControl
object
-
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.In 3.12. Applications should use separate DbControl instead.Temporarily disconnect from the database. Uncommitted changes of regular items are not lost, but you mustreconnect()
before callingcommit()
. If you have used batch items, for exampleReporterBatcher
, you should callcommit()
or you will lose everything that has already beenBasicBatcher.flush()
:ed to the database.- Throws:
ConnectionClosedException
- If connection to database has been closed.BaseException
- If there is another error
-
reconnect
Deprecated.In 3.12. Applications should use separate DbControl instead.Reconnects to the database after adisconnect()
.- Throws:
ConnectionClosedException
- If connection to database has been closed.BaseException
- If there is another error.
-
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 theDbControl
cannot be used anymore.- Specified by:
close
in interfaceAutoCloseable
-
isRolledBack
public boolean isRolledBack()If the transaction was rolled back, either as a call toclose()
or because of an error duringcommit()
. 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
Add a transactional action to this DbControl.- Since:
- 3.1
-
commit
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
Update the disk usage information for a DiskConsumable item. It is expected that theitem
parameter impements theDiskConsumable
interface and that it's data object implements theDiskConsumableData
interface.- Throws:
QuotaException
- If the quota is exceededBaseException
- If there is another error
-
getDiskUsage
Get the disk usage for the specified user at the specified location and quota type.- Throws:
BaseException
-
getDiskUsage
Get the disk usage for the specified group at the specified location and quota type.- Throws:
BaseException
-
newItem
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
Add a manual log entry to the history log. If logging is disabled this call is ignored.- Since:
- 3.9
-
loadItem
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
- TheClass
of the item objectid
- The id of the object- Returns:
- An object of the
itemClass
class - Throws:
PermissionDeniedException
- If the logged in user doesn't have read permissionBaseException
- 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 objectdataClass
- The actual data class for the object which must be compatible with the item classid
- 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
- TheClass
of the item objectdata
- 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 permissionItemNotFoundException
- If the data object is a Hibernate proxy which points to a non-existing row in the databaseBaseException
- If there is another error
-
saveItem
public void saveItem(BasicItem item) throws PermissionDeniedException, ItemAlreadyExistsException, BaseException Schedule a new item to be saved in the database. The item is saved the next time thecommit()
method is called.- Parameters:
item
- The item to be saved- Throws:
PermissionDeniedException
- If the logged in user doesn't have create permissionItemAlreadyExistsException
- If the item already exists in the databaseBaseException
- If there is another error
-
saveItemIf
Schedule a new item to be saved in the database if another item is also saved. If theitemIf
item is saved thenitem
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 assaveItem(item)
- Parameters:
itemIf
- The parent item that must be saveditem
- The item to save when the parent item is savedbefore
- TRUE if theitem
should be saved before theitemIf
, FALSE to saveitemIf
first- See Also:
-
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 thecommit()
method is called. If you are deleting multiple items it is better to useTrashcan.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 permissionItemNotFoundException
- If the item doesn't exist in the databaseBaseException
- If there is another error
-
detachItem
Detach an item from thisDbControl
. 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 toFile
items.- Parameters:
item
- The item to be detached- Throws:
BaseException
- If there is an error- See Also:
-
reattachItem
public <T extends BasicItem> T reattachItem(T item, boolean updated) throws PermissionDeniedException, ItemNotFoundException, BaseException Reattach a detached item from thisDbControl
. 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 reattachedupdated
- 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 permissionBaseException
- If there is another errorItemNotFoundException
- Since:
- 2.13
- See Also:
-
refreshItem
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
Check if an item is attached to thisDbControl
. An item is attached if it is found in either the item cache (existing items only) or commit queue (new or existing items). -
initCollection
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 aQuota
object and calls theQuota.getQuotaValue(QuotaType, Location)
method.- Parameters:
item
- The itemcollectionName
- The name of the collection- Throws:
BaseException
- If there is an error- See Also:
-
uniqueRandom
Generate a random string value that is unique for the given transaction.- Since:
- 3.4
-
addBatcher
Add aBatcher
to the batcher queue.- Parameters:
batcher
- TheBatcher
to add
-
removeBatcher
Remove aBatcher
from the batcher queue.- Parameters:
batcher
- TheBatcher
to remove
-
createTempIdTable
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
-