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

QuickStart  
A quick 2 minute intro to Morphia.
Featured
Updated Nov 19, 2011 by scotthernandez

Storing your POJOs in MongoDB?

Morphia makes that very easy. Here's what you need to do.

Libs

Go take care of getting the Dependencies for your project.

Annotate your Java classes

Let's imagine we have the following simple classes:

public class Hotel {

    private String name;
    private int stars;
    private Address address;

    // ... getters and setters
}

and

public class Address {

    private String street;
    private String city;
    private String postCode;
    private String country;

    // ... getters and setters
}

We want to save instances of these objects to MongoDB. All we need to do is add the Morphia annotations to the class fields we want to persist:

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;
import org.bson.types.ObjectId;

@Entity
public class Hotel {

    @Id private ObjectId id;

    private String name;
    private int stars;

    @Embedded
    private Address address;

    // ... getters and setters
}

and

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {

    private String street;
    private String city;
    private String postCode;
    private String country;

    // ... getters and setters
}

We've annotated Hotel with @Entity, and Address with @Embedded since the Address is an object dependent on Hotel (and does not have a life outside the Hotel).

You can see that all the basic fields are automatically mapped by Morphia. If you want to exclude a field, just annotate it with @Transient.

Also note that we had to add a new field "id" to our Hotel class. The "id" value can be any persist-able type; like an int, uuid, or other object. If you want an auto-generated value just declare it as an ObjectId. If you don't use an ObjectId you must set the value before saving.

Prepare the framework

Next, we create an instance of Morphia, and map the classes we want to use:

import com.google.code.morphia.Morphia;
...
Mongo mongo = ...;
Morphia morphia = new Morphia();
morphia.map(Hotel.class).map(Address.class);
Datastore ds = morphia.createDatastore(mongo, "my_database");
...

Mapping the classes at the beginning of your application is a good practice. It allows the system to validate your classes and prepare for storing the data, and retrieving it. You can also do a few other that are only required once at this time.

Persisting POJOs

Now we can use the Datastore instance to save classes with MongoDB. To save a Hotel in Mongo:

Hotel hotel = new Hotel();
hotel.setName("My Hotel");
hotel.setStars(4);

Address address = new Address();
address.setStreet("123 Some street");
address.setCity("Some city");
address.setPostCode("123 456");
address.setCountry("Some country");

//set address
hotel.setAddress(address);

Morphia morphia = ...;
Datastore ds = morphia.createDatastore("testDB");

// Save the POJO
ds.save(hotel);

Loading a Hotel from Mongo is also simple:

Morphia morphia = ...;
Datastore ds = morphia.createDatastore("testDB");

String hotelId = ...; // the ID of the hotel we want to load

// and then map it to our Hotel object
Hotel hotel = ds.get(Hotel.class, hotelId);

Using a query is just as simple as loading Hotel:

Morphia morphia = ...;
Datastore ds = morphia.createDatastore("testDB");

// it is easy to get four-star hotels.
List<Hotel> fourStarHotels = ds.find(Hotel.class, "stars >=", 4).asList();
//or
fourStarHotels = ds.find(Hotel.class).field("stars").greaterThenEq(4).asList();

Data Access Object (DAO) Support

To take advantage of the basic Morphia DAO support:

import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class HotelDAO extends BasicDAO<Hotel, String> {
    public HotelDAO(Morphia morphia, Mongo mongo ) {
        super(mongo, morphia, "myDB");
    }
}

HotelDAO hDAO = ...

hDAO.save(new Hotel(...));

In a web application environment, we would probably inject the Mongo, Morphia, and Datastore instances into a DAO/Service, and then inject the that into a controller, so the controller would never directly deal with Mongo or Morphia.

Comment by ap.n...@gmail.com, Jun 17, 2010

Great work, would it be possible someday to use the jpa annotations along with the morphia ones. I guess since the names are same, it would help people a lot, but it may be a good idea to support this, so that someone can done a pilot with minimal changes to his existing classes.

Comment by project member scotthernandez, Jun 28, 2010

That could be an option; file an issue and get some votes for it, or supply a patch.

It shouldn't be too hard support, but I'm not sure about mapping between the two annotation systems.

Comment by Lucifer...@gmail.com, Jan 19, 2011

why I used mapPackage (code : morphia.mapPackage("domain");), the morphia (code: datastore.ensureIndexes();) don't create index for mongo ? (unless I use map(class))

Comment by wasserma...@gmail.com, Dec 12, 2011

what about the performance? if I want load 1000 records and present in front end, mapping to 1000 objects will slow. In this case I prefer to load the record direct from mango and give them to front end.


Sign in to add a comment
Powered by Google Project Hosting