MongoDB: Easy Java Persistence with Morphia

25
Morphia: Easy Java Persistence Scott Hernandez @ 10gen

description

Easy java (POJO) persistence with Morphia and MongoDB.

Transcript of MongoDB: Easy Java Persistence with Morphia

Page 1: MongoDB: Easy Java Persistence with Morphia

Morphia: Easy Java Persistence

Scott Hernandez @ 10gen

Page 2: MongoDB: Easy Java Persistence with Morphia

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

Page 3: MongoDB: Easy Java Persistence with Morphia

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

Page 4: MongoDB: Easy Java Persistence with Morphia

BSON Package Types

int and long Array/ArrayList String byte[] – binData Double (IEEE 754 FP) Date (secs since epoch) Null Boolean JavaScript String Regex

Page 5: MongoDB: Easy Java Persistence with Morphia

MongoDB Package Mongo

Connection, ThreadSafe WriteConcern*

DB Auth, Collections getLastError() Command(), eval() RequestStart/Done

DBCollection Insert/Save/Find/Remove/Update/FindAndModify ensureIndex

Page 6: MongoDB: Easy Java Persistence with Morphia

Simple ExampleDBCollection coll = new Mongo().getDB(“test”);coll.save(

new BasicDBObjectBuilder(“name”, “scott”).append(“sex”, “male”).append(“height”, 178)).get());

Page 7: MongoDB: Easy Java Persistence with Morphia

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));

Page 8: MongoDB: Easy Java Persistence with Morphia

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”);

Page 9: MongoDB: Easy Java Persistence with Morphia

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’]}

Page 10: MongoDB: Easy Java Persistence with Morphia

Maps of Maps Can represent object graph/tree Always keyed off String (field)

Page 11: MongoDB: Easy Java Persistence with Morphia

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)

Page 12: MongoDB: Easy Java Persistence with Morphia

Annotations @Entity(“collectionName”) @Id @Reference [@Embedded] @Serialized @Transient – not java transient

@Property(“fieldAlias”)

Page 13: MongoDB: Easy Java Persistence with Morphia

Annotations -- continued @Indexes(@Index(…), @Index(…)) @Indexed(…) @AlsoLoad([aliases]) @NotSaved() @ConstructorAgs([field-names])

Page 14: MongoDB: Easy Java Persistence with Morphia

Basic POJO@Entityclass Person { @Id String name; SexEnum sex; @Indexed Integer height;}

Page 15: MongoDB: Easy Java Persistence with Morphia

Lifecycle Events @PrePersist @PreSave @PostPersist @PreLoad @PostLoad

@EntityListeners EntityInterceptor (global)

Page 16: MongoDB: Easy Java Persistence with Morphia

Lifecycle Methods@Entityclass Person { @Id String name; … Date updated; @PrePersist void prePersist() { updated = new Date(); }}

Page 17: MongoDB: Easy Java Persistence with Morphia

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()

Page 18: MongoDB: Easy Java Persistence with Morphia

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

Page 19: MongoDB: Easy Java Persistence with Morphia

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);

Page 20: MongoDB: Easy Java Persistence with Morphia

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

Page 21: MongoDB: Easy Java Persistence with Morphia

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();

Page 22: MongoDB: Easy Java Persistence with Morphia

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?

Page 23: MongoDB: Easy Java Persistence with Morphia

Update Operations set(field, val) unset(field)

inc(field, [val]) dec(field)

add(field, val) addAll(field, vals)

removeFirst/Last(field) removeAll(field, vals)

Page 24: MongoDB: Easy Java Persistence with Morphia

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

Page 25: MongoDB: Easy Java Persistence with Morphia

Questions?

Checkout Morphia:http://code.google.com/p/morphia

[email protected]