SlideShare a Scribd company logo
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

More Related Content

What's hot (18)

PPTX
MongoDB + Java - Everything you need to know
Norberto Leite
 
PPTX
Morphia, Spring Data & Co.
Tobias Trelle
 
PDF
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PDF
Indexing
Mike Dirolf
 
PDF
The emerging world of mongo db csp
Carlos Sánchez Pérez
 
PDF
ZendCon2010 Doctrine MongoDB ODM
Jonathan Wage
 
PDF
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
PPTX
Webinar: Simplifying Persistence for Java and MongoDB
MongoDB
 
KEY
Introduction to MongoDB
Alex Bilbie
 
PDF
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
PDF
Symfony2 from the Trenches
Jonathan Wage
 
PPT
Mongo-Drupal
Forest Mars
 
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
PDF
Building Apps with MongoDB
Nate Abele
 
PDF
Spring Data JPA
Cheng Ta Yeh
 
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
PDF
ORMLite Android
哲偉 楊
 
MongoDB + Java - Everything you need to know
Norberto Leite
 
Morphia, Spring Data & Co.
Tobias Trelle
 
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Indexing
Mike Dirolf
 
The emerging world of mongo db csp
Carlos Sánchez Pérez
 
ZendCon2010 Doctrine MongoDB ODM
Jonathan Wage
 
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
Webinar: Simplifying Persistence for Java and MongoDB
MongoDB
 
Introduction to MongoDB
Alex Bilbie
 
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Symfony2 from the Trenches
Jonathan Wage
 
Mongo-Drupal
Forest Mars
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
Building Apps with MongoDB
Nate Abele
 
Spring Data JPA
Cheng Ta Yeh
 
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
ORMLite Android
哲偉 楊
 

Similar to MongoDB: Easy Java Persistence with Morphia (20)

PPTX
MongoDB Aug2010 SF Meetup
Scott Hernandez
 
PPT
Java Development with MongoDB (James Williams)
MongoSF
 
PPTX
Webinar: Strongly Typed Languages and Flexible Schemas
MongoDB
 
PDF
Strongly Typed Languages and Flexible Schemas
Norberto Leite
 
PPT
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
PPTX
ExSchema
jccastrejon
 
PDF
MongodB Internals
Norberto Leite
 
ODP
Polyglot persistence with Spring Data
Corneil du Plessis
 
PPTX
Mongo+java (1)
MongoDB
 
PPT
ORM JPA
Rody Middelkoop
 
PDF
Introduction to Datastore
Software Park Thailand
 
PDF
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
PDF
Easy ORM-ness with Objectify-Appengine - Indicthreads cloud computing confere...
IndicThreads
 
PDF
An introduction into Spring Data
Oliver Gierke
 
PDF
Hands On Spring Data
Eric Bottard
 
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
PPTX
Transitioning from SQL to MongoDB
MongoDB
 
PDF
Green dao
Droidcon Berlin
 
PPTX
mongodb introduction11111111111111111111
VADAPALLYPRAVEENKUMA1
 
ODP
MongoDB San Francisco DrupalCon 2010
Karoly Negyesi
 
MongoDB Aug2010 SF Meetup
Scott Hernandez
 
Java Development with MongoDB (James Williams)
MongoSF
 
Webinar: Strongly Typed Languages and Flexible Schemas
MongoDB
 
Strongly Typed Languages and Flexible Schemas
Norberto Leite
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
ExSchema
jccastrejon
 
MongodB Internals
Norberto Leite
 
Polyglot persistence with Spring Data
Corneil du Plessis
 
Mongo+java (1)
MongoDB
 
Introduction to Datastore
Software Park Thailand
 
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
Easy ORM-ness with Objectify-Appengine - Indicthreads cloud computing confere...
IndicThreads
 
An introduction into Spring Data
Oliver Gierke
 
Hands On Spring Data
Eric Bottard
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Transitioning from SQL to MongoDB
MongoDB
 
Green dao
Droidcon Berlin
 
mongodb introduction11111111111111111111
VADAPALLYPRAVEENKUMA1
 
MongoDB San Francisco DrupalCon 2010
Karoly Negyesi
 
Ad

More from Scott Hernandez (12)

PPTX
MongoDB 2.8 Replication Internals: Fitting it all together
Scott Hernandez
 
PDF
Advanced Replication Internals
Scott Hernandez
 
PPTX
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Scott Hernandez
 
PDF
MongoDB Operational Best Practices (mongosf2012)
Scott Hernandez
 
PDF
MongoDB Datacenter Awareness (mongosf2012)
Scott Hernandez
 
PPTX
Mongo sf easy java persistence
Scott Hernandez
 
PPTX
MongoDB: Mastering the shell
Scott Hernandez
 
PPTX
MongoDB: Backup, Restore, and DR
Scott Hernandez
 
PPT
A Brief MongoDB Intro
Scott Hernandez
 
PPTX
What's new in the MongoDB Java Driver (2.5)?
Scott Hernandez
 
PPTX
MongoDB: tips, trick and hacks
Scott Hernandez
 
PPTX
Mastering the MongoDB Javascript Shell
Scott Hernandez
 
MongoDB 2.8 Replication Internals: Fitting it all together
Scott Hernandez
 
Advanced Replication Internals
Scott Hernandez
 
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Scott Hernandez
 
MongoDB Operational Best Practices (mongosf2012)
Scott Hernandez
 
MongoDB Datacenter Awareness (mongosf2012)
Scott Hernandez
 
Mongo sf easy java persistence
Scott Hernandez
 
MongoDB: Mastering the shell
Scott Hernandez
 
MongoDB: Backup, Restore, and DR
Scott Hernandez
 
A Brief MongoDB Intro
Scott Hernandez
 
What's new in the MongoDB Java Driver (2.5)?
Scott Hernandez
 
MongoDB: tips, trick and hacks
Scott Hernandez
 
Mastering the MongoDB Javascript Shell
Scott Hernandez
 
Ad

Recently uploaded (20)

PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Digital Circuits, important subject in CS
contactparinay1
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 

MongoDB: Easy Java Persistence with Morphia