Mapping Objects
Once we’ve annotated our objects, there’s a lot of heavy lifting to do. Now all we have to do is create a Morphia instance, tell Morphia what classes we want to map, and then we can
Started mapping between Mongo documents and Java objects.
Create a Morphia
instance (create a Morphia instance)
The first thing you have to do is create a Morphia instance and tell him the class you want to map. It is recommended that you only create a Morphia instance once and reuse it.
import com.google.code.morphia.Morphia;
…
Morphia morphia = new Morphia();
morphia. map(BlogEntry. class)
.map(Author.class);
…
Any class you map will be validated, and if for some reason your mapped class is invalid a MappingException will be thrown.
You can also tell Morphia to scan a package, mapping all the classes in the package.
…
morphia.mapPackage(“my.package.with.only.mongo.entities”);
…
Advanced
Usage (advanced application)
Manually use Morphia to map to DBObjects to interact directly through the java driver. Here are some examples of how to use it.
Mapping a java
for Persistence
Manually use Morphia to map to DBObjects to interact directly through the java driver. This is an example.
Let’s say we have a blog instance object and we want to save it into a container in the Mongo database. We just call the toDBObject() method in Morphia, passing in the java object.
We can save the returned DBObject directly to Mongo.
Morphia morphia = …;
Mongo mongo = …;
DB db = mongo.getDB(“BlogSite”);
BlogEntry blogEntry = …;
DBObject blogEntryDbObj = morphia.toDBObject(blogEntry);
db.getCollection(“BlogEntries”).save(blogEntryDbObj);
Now our blog instance object has been saved in Mongo.
Retrieving a java from
MongoDB (returns a Java object from Mongo)
Now let’s look at another approach: creating a Java object from a document in the Mongo database. It’s also very simple. We just call the fromDBObject() method in Morphia and pass in the DBObject object to be returned.
Morphia morphia = …;
Mongo mongo = …;
DB db = mongo.getDB(“BlogSite”);
String blogEntryId = …;
BasicDBObject blogEntryDbObj = (BasicDBObject) db.getCollection(“BlogEntries”).findOne(new BasicDBObject(“_id”, new ObjectId(blogEntryId));
BlogEntry blogEntry = morphia.fromDBObject(BlogEntry.class, blogEntryDbObj);
That’s it! Morphia removes all the error-prone code you need to manually map to/from your Java objects.
The very clear way to use Morphia to manage Java objects in your Mongdo is to use DAO
support. That method abstracts Mongo and Morphia inside a Data Access Object (DAO), so your business logic doesn’t depend on Morphia.