mongo sf easy java persistence
TRANSCRIPT
Morphia: Easy Java Persistence
Scott Hernandez @ 10gen
Library Choices Raw MongoDB Driver
Map<String, Object> view of objects Rough but dynamic
Morphia (type-safe mapper) POJOs Annotation based (similar to JPA) Syntactic sugar and helpers
Others Code generators, other jvm languages
MongoDB Java Driver BSON Package
Types Encode/Decode DBObject (Map<String, Object>)
Nested Maps Directly encoded to binary format (BSON)
MongoDB Package Mongo DBObject (BasicDBObject/Builder) DB/DBColletion DBQuery/DBCursor
BSON Package Types
int and long Array/ArrayList String byte[] – binData Double (IEEE 754 FP) Date (secs since epoch) Null Boolean JavaScript String Regex
MongoDB Package Mongo
Connection, ThreadSafe WriteConcern*
DB Auth, Collections getLastError() Command(), eval() RequestStart/Done
DBCollection Insert/Save/Find/Remove/Update/FindAndModify ensureIndex
Simple ExampleDBCollection coll = new Mongo().getDB(“test”);coll.save(
new BasicDBObjectBuilder(“name”, “scott”).append(“sex”, “male”).append(“height”, 178)).get());
Simple Example, AgainDBCollection coll = 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”);
ListsDBObject dbObj = 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 Maps Can represent object graph/tree Always keyed off String (field)
Morphia: MongoDB Mapper Maps POJO (through fields) Type-safe/preserving Access Patterns: DAO/Datastore/+more Data Types Performs well JPA like Many 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
@EntityListeners EntityInterceptor (global)
Lifecycle Methods@Entityclass Person { @Id String name; … Date updated; @PrePersist void prePersist() { updated = new Date(); }}
Datastore Basics get(class, id) – single Entity by id find(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 fields Push/pop arrays (lists) Increment numeric fields
Any combination of the above Merge
Get/Save or Update
Add, Get, DeletePerson me = new Person(“scott”, Sex.Male,
179)
Datastore ds = new Morphia().createDatastore(“bar”)
ds.save(me);
Person meAgain = ds.get(Person.class, “scott”)
ds.delete(me);
Queries Based on Entity (Class) Validated (default) Fluent Or and Geo Support Type Converted Params Reusable Returned as
Keys (or @Id only instances) List Iterable
Simple QueryDatastore ds = …
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();
UpdateDatastore ds = …Query q = ds.find(Person.class, “name”,
“scott”);UpdateOperation uo =
ds.createUpdateOperations(cls)
uo.set(“city”, “seattle”).set(“lastUpdated”, new Date());
UpdateResults res = ds.update(q, uo);if(res.getUpdatedCount() > 0) //do something?
Update Operations set(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 Entity Update
@Reference Stored as DBRef(s) Loaded with Entity Not automatically saved Lazy (w/proxy)
Key<T> Stored as DBRef(s) Just a link, but resolvable by Datastore/Query
Questions?
Checkout Morphia:http://code.google.com/p/morphia