Life Cycle Methods
There are various annotations which can be used to register callbacks on certain life cycle events. These include Pre/Post-Persist (Save) , and Pre/Post-Load.
-
@PrePersist
- Called before save, it can return aDBObject
in place of an empty one. -
@PreSave
- Called right beforeDBCollection.save()
is called. Changes made to the entity will not be persisted; theDBObject
can be passed as an argument (you can add/remove/change values) -
@PostPersist
- Called after the save call to the database -
@PreLoad
- Called before mapping the document from the database to the entity; the DBObject is passed as an argument (you can add/remove/change values) -
@PostLoad
- Called after populating the entity with the values from the document
See the annotations guide for a full list of the annotations supported.
Examples
Here is a one of the test classes.
All parameters and return values are options in your implemented methods.
Example
Here is a simple example of an entity that always saves the Date it was last updated. Alternatively, the resulting serialized form can be passed back in just prior to sending the document to the database.
class BankAccount {
@Id
String id;
Date lastUpdated = new Date();
@PrePersist
public void trackUpdate() {
lastUpdated = new Date();
}
@PrePersist
public void prePersist( DBObject dbObj) {
// perform operations on serialized form of the entity
}
}
EntityListeners
If your application has more generalized life cycle events, these methods can be stored on classes external to your model. For example’s sake, let’s assume there’s a need to digitally sign all documents before storing it in the database.
@EntityListeners(DigitalSigner.class)
public class BankAccount {
@Id
String id;
Date lastUpdated = new Date();
}
class DigitalSigner {
@PrePersist
void prePersist( Object entity, DBObject dbObject) {
dbObject.put("signature", sign(dbObject));
}
}