Community contributed extensions

Use of PlayMorphia model: CRUD

Once you have created your PlayMorphia model class it’s easy to use it through your application.

Create an new model instance

There is nothing more than initializing an object and call save() method on it to create an new model instance:

User user = new User();

Read model from MongoDB

To read a model from MongoDB you will need the ID object. The following sample code shows how to read User model from MongoDB in a controller:

public static void show(String userId) {
    User user = User.findById(userId);

You can always pass in java.lang.String type object into Model.findById() method without regarding to the real ID field type. PlayMorphia model will automatically handle the type conversion.

Update model

Once you read a model from MongoDB you can modify it’s properties and then call save() method on the model instance to update the modified properties into MongoDB. The following sample code change the user’s role to “admin” and save the updates to MongoDB:

User user = User.findById(userId);
user.role = "admin";;

Batch update

Batch update not directly supported in PlayMorphia yet, but it’s easy to do via the morphia Datastore interface:

Query smartGuys = Employee.find("department", "IT").getMorphiaQuery();
Datastore ds = Employee.ds();
UpdateOperations incSalary = 
    ds.createUpdateOperations(Employee.class).inc("salary", 10000);
ds.update(smartGuys, incSalary);

Refer to Morphia documentation for more about updating

Delete model

Call delete() method on the model object if you want to delete the document it corresponding to in MongoDB:

User user = User.findById(userId);

Batch delete

It’s easy to do batch delete via MorphiaQuery interface:

Student.q().filter("score < ", 60).delete();

To delete all record of a collection, you can do either one of the following:


See also

  1. Understanding PlayMorphia model
  2. Using Query
  3. Introduction to lifecycle event handling