SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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哲偉 楊
 

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

Similaire à MongoDB: Easy Java Persistence with Morphia

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
 

Similaire à MongoDB: Easy Java Persistence with Morphia (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
 

Plus 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
 

Plus 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
 

Dernier

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Dernier (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

MongoDB: Easy Java Persistence with Morphia

  • 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