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();
...
user.save()
Batch Insert
PlayMorphia-1.2.8 add support to batch insert. Suppose you have a list of model constructed, before v1.2.8 you do it using the following code:
List<MyModel> myModels = ...;
for (MyModel model: myModels) model.save();
Now you do it as follows:
List<MyModel> myModels = ...;
MyModel.insert(myModels);
Note this is not a simple syntax sugar but instead it will call to DBCollection.insert(List<DBObject>)
interface.
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) {
notFoundIfNull(userId);
User user = User.findById(userId);
notFoundIfNull(user);
render(user);
}
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";
user.save();
Batch update
Batch update not directly supported in PlayMorphia yet, but it’s easy to do via the morphia Datastore
interface:
Before v1.2.6 you do batch update like this:
Datastore ds = Employee.ds();
UpdateOperations op = ds.createUpdateOperations(Employee.class);
UpdateOperations<Employee> op = ds.createUpdateOperations(Employee.class).inc("salary", 10000).inc("bonus", 99999);
Query<Employee> q = (Query<Employee>)Employee.q().findBy("department", "IT").getMorphiaQuery();
ds.update(q, op);
Now you do it this way:
Employee.o().inc("salary, bonus", 10000, 99999).update("department", "IT");
util v1.2.6 PlayMorphia does NOT provide lifecycle events for batch update yet
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);
user.delete();
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:
User.deleteAll();
User.q().delete();