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 aDocument
in place of an empty one. -
@PostPersist
- Called after the save call to the database -
@PreLoad
- Called before mapping the document from the database to the entity; the Document is passed as an argument (you can add/remove/change values) -
@PostLoad
- Called after populating the entity with the values from the document
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( Document document) {
// 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, Document document) {
document.put("signature", sign(document));
}
}
No Delete Support Because deletes are usually done with queries there is no way to support a Delete lifecycle event. |