Morphia: Easy Java PersistenceScott Hernandez @ 10gen
Library ChoicesRaw MongoDB DriverMap<String, Object> view of objectsRough but dynamicMorphia (type-safe mapper)POJOsAnnotation based (similar to JPA)Syntactic sugar and helpersOthersCode generators, other jvm languages
MongoDB Java DriverBSON PackageTypesEncode/DecodeDBObject (Map<String, Object>)Nested MapsDirectly encoded to binary format (BSON)MongoDB PackageMongoDBObject (BasicDBObject/Builder)DB/DBColletionDBQuery/DBCursor
BSON PackageTypesint and longArray/ArrayListStringbyte[] – binDataDouble (IEEE 754 FP)Date (secs since epoch)NullBooleanJavaScript StringRegex
MongoDB PackageMongoConnection, ThreadSafeWriteConcern*DBAuth, Collections getLastError()Command(), eval()RequestStart/DoneDBCollectionInsert/Save/Find/Remove/Update/FindAndModifyensureIndex
Simple ExampleDBCollectioncoll = new Mongo().getDB(“test”);coll.save(	new BasicDBObjectBuilder(“name”, “scott”).		append(“sex”, “male”).			append(“height”, 178)).get());
Simple Example, AgainDBCollectioncoll = new Mongo().getDB(“test”).getCollection(“people”);Map<String, Object> fields = new …fields.add(“name”, “scott”); fields.add(“sex”, “male”);fields.add(“height”, 178);coll.insert(new BasicDBObject(fields));
DBObject <-> (B/J)SON{name:”scott”, sex:“male”, height: 178 }new BasicDBObjectBuilder().append(“name”, “scott”) .append(“sex”, “male”) .append(“height”, 178) .get();String name = (String)dbObj.get(“name”);
ListsDBObjectdbObj = JSON.parse(“	{‘name’:’scott’,height: 178, sex:’male’}”);List<String> activities = new …activities.add(“mongodb”);activities.add(“java”);dbObj.put(“activities”, activities);{…, activities: [‘mongodb’, ‘java’]}
Maps of MapsCan represent object graph/treeAlways keyed off String (field)
Morphia: MongoDB MapperMaps POJO (through fields)Type-safe/preservingAccess Patterns: DAO/Datastore/+moreData TypesPerforms wellJPA likeMany concepts came from Objectify (GAE)
Annotations@Entity(“collectionName”)@Id@Reference[@Embedded]@Serialized@Transient – not java transient@Property(“fieldAlias”)
Annotations -- continued@Indexes(@Index(…), @Index(…))@Indexed(…)@AlsoLoad([aliases])@NotSaved()@ConstructorAgs([field-names])
Basic POJO@Entityclass Person {@Id  String name;SexEnum sex;@Indexed  Integer height;}
Lifecycle Events@PrePersist@PreSave@PostPersist@PreLoad@PostLoad@EntityListenersEntityInterceptor (global)
Lifecycle Methods@Entityclass Person {@Id String name;  …  Date updated;  @PrePersist  void prePersist() {     updated = new Date();  }}
Datastore Basicsget(class, id) – single Entity by idfind(class, […]) – multiple Entities (by query)save(entity, […])delete(query)	getCount(query) – also find(…).count()update/First(query, ops)findAndModify/Delete(query, ops)merge(doc)mapReduce(type, query, map, reduce, …)EnsureIndexes()/EnsureCaps()
Save whole object graphs (get/save)Update parts (embedded objects)Un/set fieldsPush/pop arrays (lists)Increment numeric fieldsAny combination of the aboveMergeGet/Save or Update
Add, Get, DeletePerson me = new Person(“scott”, Sex.Male, 179)Datastoreds = new Morphia().createDatastore(“bar”)ds.save(me);Person meAgain = ds.get(Person.class, “scott”)ds.delete(me);
QueriesBased on Entity (Class)Validated (default)FluentOr and Geo SupportType Converted ParamsReusableReturned as Keys (or @Id only instances)ListIterable
Simple QueryDatastoreds = …Query q = ds.createQuery(Person.class);q.field(“height”).greaterThan(155).limit(5);for(Person p : q.fetch())   print(p);Person me = q.field(“name”).startsWith(“sc”).get();
UpdateDatastoreds = …Query q = ds.find(Person.class, “name”, “scott”);UpdateOperationuo = ds.createUpdateOperations(cls)uo.set(“city”, “seattle”).set(“lastUpdated”, new Date());UpdateResults res = ds.update(q, uo);if(res.getUpdatedCount() > 0)  //do something?
Update Operationsset(field, val)unset(field)inc(field, [val])dec(field)add(field, val)addAll(field, vals)removeFirst/Last(field)removeAll(field, vals)
Relationships[@Embedded]Loaded/Saved with EntityUpdate@ReferenceStored as DBRef(s)Loaded with EntityNot automatically savedLazy (w/proxy)Key<T>Stored as DBRef(s)Just a link, but resolvable by Datastore/Query
Questions?Checkout Morphia:http://code.google.com/p/morphiaScottHernandez@gmail.com

Mongo sf easy java persistence