Callbacks are hooks that are being called when beans are manipulated through the GenericQueryManager
or other query managers that are based on it (ContentQueryManager
, for instance). They can either be implemented directly by implementing the Callbacks
interface, or they can be provided by a bean by implementing the CallbacksProvider
interface. The latter allows a bean to use the convenience AbstractCallbacks
class and to only implement the methods that are needed. Callbacks can for example be used to delete associated and dependent objects when delete is called (by implementing beforeDelete(int)
), or to clear a cache when an object has been modified (by implementing afterSave(Object, boolean)
and afterDelete(int, boolean)
). The return value of callbacks can be used to cancel actions. When the before* callbacks return false, the associated actions are cancelled. When the after* callbacks return false, the execution of the action is interrupted at that step and no further callbacks will be called.
We use this for example in Bamboo to update the message and topic counts each time a message is saved or deleted, like this:
public class Message extends Validation<ConstrainedBean, ConstrainedProperty> implements CallbacksProvider<Message>
{
...
public Callbacks<Message> getCallbacks()
{
return new AbstractCallbacks<Message>() {
private Datasource mDatasource = ...;
private MessageQueryManager mMessages = MessageQueryManagerFactory.getInstance(mDatasource);
private Message mDeletedMessage = null;
public boolean afterSave(Message object, boolean success)
{
if (success)
{
mMessages.updateCachedObjectCounts(object);
}
return true;
}
public boolean beforeDelete(int objectId)
{
mDeletedMessage = mMessages.getMessage(objectId);
return true;
}
public boolean afterDelete(int objectId, boolean success)
{
if (success)
{
mMessages.updateCachedObjectCounts(mDeletedMessage);
}
return true;
}
};
}
...
}