My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for

LifecycleMethods  
A list of Annotation to decorate your Entity with for lifecycle events.
Updated Nov 30, 2010 by scotthernandez

Lifecycle Method Annotations

There are various annotations which can be used to register callbacks on certain lifecycle events. These include Pre/Post-Persist (Save), and Pre/Post-Load.

  • @PrePersist - Called before save, it can return a DBObject in place of an empty one.
  • @PostPersist - Called after the save call to the datastore
  • @PreLoad - Called before mapping the datastore object to the entity (POJO); the DBObject is passed as an argument (you can add/remove/change values)
  • @PostLoad - Called after mapping to the entity

See the AllAnnotation for a full list of the annotations supported.

Examples

Here is a one of the test classes: http://code.google.com/p/morphia/source/browse/trunk/morphia/src/test/java/com/google/code/morphia/TestDatastore.java#82

All parameters and return values are options in your implemented methods.

Simple @PrePersist

Here is a simple example of an entity that always saves the Date it was last updated at.

class BankAccount {
  @Id String id;
  Date lastUpdated = new Date();

  @PrePersist void prePersist() {lastUpdated = new Date();}
}

EntityListerners

In addition, you can separate the lifecycle event implementation in an external class, or many.

@EntityListeners(BackAccountWatcher.class)
class BankAccount {
  @Id String id;
  Date lastUpdated = new Date();
}

class BankAccountWatcher{
  
  @PrePersist void prePersist(BankAccount act) {act.lastUpdated = new Date();}

}

No Delete Support

Because deletes are usually done with queries there is no way to support a Delete lifecycle event. If, or when, server-side triggers are enabled there may be some support for this, but even then it will be hard to imagine how this would logically fit.

Comment by dave.tro...@gmail.com, Oct 4, 2010

Lifecycle methods appear to be able to be declared with zero, one, or two arguments:

@<LifeCycleEventAnnotation> DBObject lifecycleMethod(DBObject dbObj, Mapper mapper);

- with/ arguments left off the right as required.

The return value appears to be utilized as follows:

  • PrePersist? - Persisted fields are updated/appended to returned DBObject
  • PreSave? - Value ignored.
  • PreLoad? - Persisted values are restored to the DBObject if not present before mapping to POJO
  • PostLoad? - Value ignored.
Comment by ostraz, Mar 26, 2012

'EntityListerners?' -> EntityListeners?

@link(See the AllAnnotation? for a full list of the annotations supported.) -> http://code.google.com/p/morphia/wiki/AllAnnotations


Sign in to add a comment
Powered by Google Project Hosting