SlideShare una empresa de Scribd logo
1 de 25
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 Example DBCollectioncoll = new Mongo().getDB(“test”); coll.save( 	new BasicDBObjectBuilder(“name”, “scott”). 		append(“sex”, “male”). 			append(“height”, 178)).get());
Simple Example, Again DBCollectioncoll = 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”);
Lists DBObjectdbObj = 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] ,[object Object],@Transient – not java transient @Property(“fieldAlias”)
Annotations -- continued @Indexes(@Index(…), @Index(…)) @Indexed(…) @AlsoLoad([aliases]) @NotSaved() @ConstructorAgs([field-names])
Basic POJO @Entity class Person { @Id   String name; SexEnum sex; @Indexed   Integer height; }
Lifecycle Events @PrePersist @PreSave @PostPersist @PreLoad @PostLoad @EntityListeners EntityInterceptor (global)
Lifecycle Methods @Entity class 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, Delete Person 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);
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 Query Datastoreds = … 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();
Update Datastoreds = … 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 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 ScottHernandez@gmail.com

Más contenido relacionado

La actualidad más candente

MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Tobias Trelle
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBMongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBAlex Bilbie
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMJonathan Wage
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBUwe Printz
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDBNate Abele
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDoug Green
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android哲偉 楊
 

La actualidad más candente (19)

MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Indexing
IndexingIndexing
Indexing
 
The emerging world of mongo db csp
The emerging world of mongo db   cspThe emerging world of mongo db   csp
The emerging world of mongo db csp
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDBWebinar: Simplifying Persistence for Java and MongoDB
Webinar: Simplifying Persistence for Java and MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
 
ORMLite Android
ORMLite AndroidORMLite Android
ORMLite Android
 

Similar a Easy Java Persistence with Morphia Library

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)MongoSF
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Andrii Lashchenko
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Groupkchodorow
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriverchristkv
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring DataEric Bottard
 

Similar a Easy Java Persistence with Morphia Library (20)

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 
Green dao
Green daoGreen dao
Green dao
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
DataMapper
DataMapperDataMapper
DataMapper
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
Latinoware
LatinowareLatinoware
Latinoware
 

Más de Scott Hernandez

MongoDB 2.8 Replication Internals: Fitting it all together
MongoDB 2.8 Replication Internals: Fitting it all togetherMongoDB 2.8 Replication Internals: Fitting it all together
MongoDB 2.8 Replication Internals: Fitting it all togetherScott Hernandez
 
Advanced Replication Internals
Advanced Replication InternalsAdvanced Replication Internals
Advanced Replication InternalsScott Hernandez
 
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Realtime Analytics with MongoDB Counters (mongonyc 2012)Realtime Analytics with MongoDB Counters (mongonyc 2012)
Realtime Analytics with MongoDB Counters (mongonyc 2012)Scott Hernandez
 
MongoDB Operational Best Practices (mongosf2012)
MongoDB Operational Best Practices (mongosf2012)MongoDB Operational Best Practices (mongosf2012)
MongoDB Operational Best Practices (mongosf2012)Scott Hernandez
 
MongoDB Datacenter Awareness (mongosf2012)
MongoDB Datacenter Awareness (mongosf2012)MongoDB Datacenter Awareness (mongosf2012)
MongoDB Datacenter Awareness (mongosf2012)Scott Hernandez
 
Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistenceScott Hernandez
 
MongoDB: Mastering the shell
MongoDB: Mastering the shellMongoDB: Mastering the shell
MongoDB: Mastering the shellScott Hernandez
 
MongoDB: Backup, Restore, and DR
MongoDB: Backup, Restore, and DRMongoDB: Backup, Restore, and DR
MongoDB: Backup, Restore, and DRScott Hernandez
 
What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?Scott Hernandez
 
MongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF MeetupMongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF MeetupScott Hernandez
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksScott Hernandez
 
Mastering the MongoDB Javascript Shell
Mastering the MongoDB Javascript ShellMastering the MongoDB Javascript Shell
Mastering the MongoDB Javascript ShellScott Hernandez
 

Más de Scott Hernandez (13)

MongoDB 2.8 Replication Internals: Fitting it all together
MongoDB 2.8 Replication Internals: Fitting it all togetherMongoDB 2.8 Replication Internals: Fitting it all together
MongoDB 2.8 Replication Internals: Fitting it all together
 
Advanced Replication Internals
Advanced Replication InternalsAdvanced Replication Internals
Advanced Replication Internals
 
Realtime Analytics with MongoDB Counters (mongonyc 2012)
Realtime Analytics with MongoDB Counters (mongonyc 2012)Realtime Analytics with MongoDB Counters (mongonyc 2012)
Realtime Analytics with MongoDB Counters (mongonyc 2012)
 
MongoDB Operational Best Practices (mongosf2012)
MongoDB Operational Best Practices (mongosf2012)MongoDB Operational Best Practices (mongosf2012)
MongoDB Operational Best Practices (mongosf2012)
 
MongoDB Datacenter Awareness (mongosf2012)
MongoDB Datacenter Awareness (mongosf2012)MongoDB Datacenter Awareness (mongosf2012)
MongoDB Datacenter Awareness (mongosf2012)
 
Mongo sf easy java persistence
Mongo sf   easy java persistenceMongo sf   easy java persistence
Mongo sf easy java persistence
 
MongoDB: Mastering the shell
MongoDB: Mastering the shellMongoDB: Mastering the shell
MongoDB: Mastering the shell
 
MongoDB: Backup, Restore, and DR
MongoDB: Backup, Restore, and DRMongoDB: Backup, Restore, and DR
MongoDB: Backup, Restore, and DR
 
A Brief MongoDB Intro
A Brief MongoDB IntroA Brief MongoDB Intro
A Brief MongoDB Intro
 
What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?What's new in the MongoDB Java Driver (2.5)?
What's new in the MongoDB Java Driver (2.5)?
 
MongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF MeetupMongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF Meetup
 
MongoDB: tips, trick and hacks
MongoDB: tips, trick and hacksMongoDB: tips, trick and hacks
MongoDB: tips, trick and hacks
 
Mastering the MongoDB Javascript Shell
Mastering the MongoDB Javascript ShellMastering the MongoDB Javascript Shell
Mastering the MongoDB Javascript Shell
 

Último

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Easy Java Persistence with Morphia Library

  • 1. Morphia: Easy Java Persistence Scott Hernandez @ 10gen
  • 2. 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
  • 3. 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
  • 4. BSON Package Types int and long Array/ArrayList String byte[] – binData Double (IEEE 754 FP) Date (secs since epoch) Null Boolean JavaScript String Regex
  • 5. MongoDB Package Mongo Connection, ThreadSafe WriteConcern* DB Auth, Collections getLastError() Command(), eval() RequestStart/Done DBCollection Insert/Save/Find/Remove/Update/FindAndModify ensureIndex
  • 6. Simple Example DBCollectioncoll = new Mongo().getDB(“test”); coll.save( new BasicDBObjectBuilder(“name”, “scott”). append(“sex”, “male”). append(“height”, 178)).get());
  • 7. Simple Example, Again DBCollectioncoll = 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));
  • 8. 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”);
  • 9. Lists DBObjectdbObj = 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’]}
  • 10. Maps of Maps Can represent object graph/tree Always keyed off String (field)
  • 11. 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)
  • 12.
  • 13. Annotations -- continued @Indexes(@Index(…), @Index(…)) @Indexed(…) @AlsoLoad([aliases]) @NotSaved() @ConstructorAgs([field-names])
  • 14. Basic POJO @Entity class Person { @Id String name; SexEnum sex; @Indexed Integer height; }
  • 15. Lifecycle Events @PrePersist @PreSave @PostPersist @PreLoad @PostLoad @EntityListeners EntityInterceptor (global)
  • 16. Lifecycle Methods @Entity class Person { @Id String name; … Date updated; @PrePersist void prePersist() { updated = new Date(); } }
  • 17. 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()
  • 18. 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
  • 19. Add, Get, Delete Person 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);
  • 20. 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
  • 21. Simple Query Datastoreds = … 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();
  • 22. Update Datastoreds = … 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?
  • 23. Update Operations set(field, val) unset(field) inc(field, [val]) dec(field) add(field, val) addAll(field, vals) removeFirst/Last(field) removeAll(field, vals)
  • 24. 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
  • 25. Questions? Checkout Morphia: http://code.google.com/p/morphia ScottHernandez@gmail.com