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

GettingStarted  
Things you need to do before you can start using Morphia.
Updated Dec 6, 2010 by scotthernandez

Getting Started

You will need Java SE 5 or higher. You will also need access to a Mongo database (http://mongodb.org). Please take a look at the rest of the Dependencies.

This will consist of a few code snippets to get you going!

First Entity

@Entity
class MyEntity {
  @Id ObjectId id;
  String name;
}

Initialize Morphia/Mongo

Datastore ds = new Morphia().createDatastore("myDB"); //best to use (Mongo, String) method, where Mongo is a singleton.

...

//at application start
ds.ensureIndexes(); //creates indexes from @Index annotations in your entities
ds.ensureCaps(); //creates capped collections from @Entity

Saving

MyEntity e = ...;

ds.save(e);

Querying

MyEntity e = ds.find(MyEntity.class).get(); //get the first one by type
MyEntity e = ds.find(MyEntity.class).field("name").equal("someName").get(); //get the first one where name = "someName"

Datastore

The datastore represents a type-safe wrapper against the basic mongodb operations (find, save, delete). For each operation you can specify the class type you are working with and parameters to the operation.

see more at the Datastore page...

Comment by richsew...@gmail.com, Sep 24, 2011

Capped collections with indexes:

//at application start 
ds.ensureIndexes(); //creates indexes from @Index annotations in your entities 
ds.ensureCaps(); //creates capped collections from @Entity

If you have an index on a capped collection, then ensuring the index will create the collection uncapped if it did not already exist. Therefore you will not get a capped collection.

To solve this problem, reverse the 'ensure' order:

ds.ensureCaps(); //creates capped collections from @Entity 
ds.ensureIndexes(); //creates indexes from @Index annotations in your entities

Sign in to add a comment
Powered by Google Project Hosting