SlideShare a Scribd company logo
MongoDB Persistence
with Java and Morphia
Justin Lee
Software Engineer, MongoDB
Agenda
Introduction
Getting Started
Modeling
Querying
Updating
Indexing
Road Map
What is Morphia?
•

Object document mapper — https://github.com/mongodb/morphia

•

Provides mapping to/from Java objects to mongodb

•

Annotation-based

•

Embedded objects/documents

•

References (lazy or eager)

•

Fluent query/update APIs

•

Runtime validation
Why Morphia?
•

Offload object marshaling
•

automatically keeps up as objects evolve: new, removed, renamed

•

Higher abstraction

•

Simplified management of indexes

•

Unify code with schema management

•

Object/Document Versioning
A Brief History
•

Created by Scott Hernandez

•

Hired by 10Gen —> started working on the kernel

•

Morphia left alone for a couple of years

•

Lots of uncertainty

•

James Green forked morphia

•

I was hired in June, 2013 in part to pick up Morphia

•

5 releases since with another pending
Getting Started
Adding morphia — Maven
<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>0.105</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.3</version>
</dependency>
Adding morphia — Gradle
compile "org.mongodb.morphia:morphia:0.105"
compile "org.mongodb:mongo-java-driver:2.11.3"
!
!
Initializing morphia
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(
new MongoClient(), “morphia-demo");
morphia.mapPackage("org.mongodb.morphia.demo");
datastore.ensureIndexes();
!
Entity Modeling
Basic Entity
@Entity
public class GithubUser {

private String userName;
private String fullName;
!

private Date memberSince;
}
Basic Entity
@Entity (value = “users")
public class GithubUser {

private String userName;
private String fullName;
!

private Date memberSince;
}
Basic Entity
@Entity (value = "users", noClassnameStored = true)
public class GithubUser {

private String userName;
private String fullName;
!

private Date memberSince;
}
Basic Entity
@Entity (value = "users", noClassnameStored = true)
public class GithubUser {
@Id
private String userName;
private String fullName;
!

private Date memberSince;
}
Basic Entity
@Entity (value = "users", noClassnameStored = true)
public class GithubUser {
@Id
private String userName;
private String fullName;
!

}

@Property("since")
private Date memberSince;
Basic Entity — Saving
GithubUser user = new GithubUser("evanchooly");
user.fullName = "Justin Lee";
user.memberSince = sdf.parse("6-15-1987");
datastore.save(user);
Basic Entity — Shell
repl0:PRIMARY> db.users.findOne()
{
"_id" : "evanchooly",
"fullName" : "Justin Lee",
"since" : ISODate("1987-06-15T04:00:00Z")
}
Complex Entities
@Entity("orgs")
public class Organization {
@Id
public String name;
!

}

public Organization(final String name) {
this.name = name;
}
Complex Entities
@Embedded
public class Settings {
public String defaultBranch = "master";
public Boolean allowWiki = false;
public Boolean allowIssues = true;
}
Complex Entities
@Entity("repos")
public class Repository {
@Id
public String name;
@Reference
public Organization organization;
@Reference
public GithubUser owner;
public Settings settings = new Settings();
}
Complex Entities
@Entity(value = "users", noClassnameStored = true)
public class GithubUser {
@Id
public final String userName;
public String fullName;
@Property("since")
public Date memberSince;
@Reference(lazy = true)
public List<Repository> repositories = new
ArrayList<>();
}
Complex Entities
Organization org = new Organization("mongodb");
!

GithubUser user = new GithubUser("evanchooly");
user.fullName = "Justin Lee";
user.memberSince = sdf.parse("6-15-1987");
!

datastore.save(org);
datastore.save(user);
!

datastore.save(new Repository(org, "morphia"));
datastore.save(new Repository(user, "morphia"));
Complex Entities — Shell
repl0:PRIMARY> show collections
orgs
repos
system.indexes
users
Complex Entities — Shell
repl0:PRIMARY> db.orgs.findOne();
{ "_id" : "mongodb", "className" :
"org.mongodb.morphia.demo.Organization" }
Complex Entities — Shell
repl0:PRIMARY> db.repos.find().pretty();
{
"_id" : "mongodb/morphia",
"className" : "org.mongodb.morphia.demo.Repository",
"organization" : DBRef("orgs", "mongodb"),
"settings" : {
"defaultBranch" : "master",
"allowWiki" : false,
"allowIssues" : true
}
}
{
"_id" : "evanchooly/morphia",
"className" : "org.mongodb.morphia.demo.Repository",
"owner" : DBRef("users", "evanchooly"),
"settings" : {
…
}
}
Complex Entities — Shell
repl0:PRIMARY> db.users.findOne();
{
"_id" : "evanchooly",
"fullName" : "Justin Lee",
"since" : ISODate("1987-06-15T04:00:00Z"),
"repositories" : [
DBRef("repos", "mongodb/morphia"),
DBRef("repos", "evanchooly/morphia")
]
}
Queries
Basic Query
Query<Repository> query =
datastore.createQuery(Repository.class);
Repository repository = query.get();
!

runQuery called morphia-demo.repos {}
!

List<Repository> repositories = query.asList();
!

runQuery called morphia-demo.repos {}
!

Iterable<Repository> fetch = query.fetch();
!

… ?
Basic Query
Query<Repository> query =
datastore.createQuery(Repository.class);
query.field("owner").equal(evanchooly).get();
!

runQuery called morphia-demo.repos { owner: { $ref:
"users", $id: "evanchooly" } }
Complex Entities
@Entity("repos")
public class Repository {
@Id
public String name;
@Reference
public Organization organization;
@Reference
public GithubUser owner;
public Settings settings = new Settings();
}
Basic Query — @Property
@Entity(value = "users", noClassnameStored = true)
public class GithubUser {
@Id
private String userName;
private String fullName;
@Property("since")
private Date memberSince;
}
Basic Query — @Property
datastore.createQuery(GithubUser.class)
.field("memberSince").equal(date).get();
!

GithubUser{userName='evanchooly', fullName='Justin
Lee', memberSince=Mon Jun 15 00:00:00 EDT 1987}
!

datastore.createQuery(GithubUser.class)
.field("since").equal(date).get();
!

GithubUser{userName='evanchooly', fullName='Justin
Lee', memberSince=Mon Jun 15 00:00:00 EDT 1987}
Updates
Updating Entities
evanchooly.followers = 12;
datastore.save(evanchooly);
Multiple Updates
UpdateOperations<GithubUser> update =
datastore.createUpdateOperations(
GithubUser.class)
.inc("followers").set("following", 42);
Query<GithubUser> query =
datastore.createQuery(GithubUser.class)
.field(“followers”)
.equal(0);
datastore.update(query, update);
!

update morphia-demo.users query: { followers: 0 }
update: { $set: { following: 42 }, $inc:
{ followers: 1 } }
Versioned Updates
@Entity("orgs")
public class Organization {
@Id
public String name;
@Indexed
public Date created;
@Version(“v”)
private long version;
!

…
!

}
Versioned Updates
Organization organization =
datastore.createQuery(Organization.class).get();
Organization organization2 =
datastore.createQuery(Organization.class).get();
!

datastore.save(organization); // fine
datastore.save(organization); // fine
datastore.save(organization2);
!

java.util.ConcurrentModificationException: Entity
of class org.mongodb.morphia.demo.Organization
(id='mongodb',version='1') was concurrently
updated.
Indexes
Indexes — Fields
@Entity("orgs")
public class Organization {
@Id
public String name;
@Indexed(value = IndexDirection.ASC, unique = false,
name = "", dropDups = false, background = false,
sparse = false, expireAfterSeconds = -1)
public Date created;
!
…
}
Indexes — Fields
repl0:PRIMARY> db.orgs.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "morphia-demo.orgs"
},
{
"v" : 1,
"key" : {
"created" : 1
},
"name" : "created_1",
"ns" : "morphia-demo.orgs"
}
]
Indexes — Classes
@Entity(value = "users", noClassnameStored = true)
@Indexes({
@Index(value ="userName, -followers", name = "popular")
})
public class GithubUser {
@Id
public String userName;
public String fullName;
@Property("since")
public Date memberSince;
public Date lastActive;
@Reference(lazy = true)
public List<Repository> repositories = new ArrayList<>();
public int followers = 0;
public int following = 0;

!

…
What’s Next
The Road to 1.0
•

It’s short

•

Aggregation support

•

Text Searching

•

Improved geo support

•

Handful of bug fixes
Resources
•

Morphia Homepage https://github.com/mongodb/morphia

•

Discussions Forum https://groups.google.com/forum/#!forum/
morphia

•

This presentation and code https://github.com/evanchooly/morphiademo
Questions?
MongoDB Persistence
with Java and Morphia
Justin Lee
Software Engineer, MongoDB

More Related Content

PPTX
Project risk management: Techniques and strategies
PPTX
00 Introduction of project scheduling
PPTX
Work breakdown structure
PPT
Electrical superintendent recommendation letter
PDF
Project planning and scheduling
PPTX
Intro to Project Management .pptx
PPTX
The role of the project manager
PDF
An introduction to MongoDB
Project risk management: Techniques and strategies
00 Introduction of project scheduling
Work breakdown structure
Electrical superintendent recommendation letter
Project planning and scheduling
Intro to Project Management .pptx
The role of the project manager
An introduction to MongoDB

Viewers also liked (18)

PPTX
MongoDB: Easy Java Persistence with Morphia
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PPTX
Simplifying Persistence for Java and MongoDB with Morphia
PDF
MongoDB Hacks of Frustration
PDF
Get your Spatial on with MongoDB in the Cloud
PPTX
Mango Database - Web Development
PDF
Introduction to MongoDB
KEY
Graphs, Edges & Nodes - Untangling the Social Web
PPTX
Partner Recruitment Webinar: "Join the Most Productive Ecosystem in Big Data ...
PDF
Java development with MongoDB
PDF
Designing and Building a Graph Database Application – Architectural Choices, ...
PPTX
Concurrency Patterns with MongoDB
KEY
JSON-LD and MongoDB
PPTX
Introduction to Graph Databases
PDF
Node.js vs Play Framework
PDF
Webinar: 10-Step Guide to Creating a Single View of your Business
PDF
Neo4j - 5 cool graph examples
PDF
Data Modeling with Neo4j
MongoDB: Easy Java Persistence with Morphia
Morphia: Simplifying Persistence for Java and MongoDB
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB Hacks of Frustration
Get your Spatial on with MongoDB in the Cloud
Mango Database - Web Development
Introduction to MongoDB
Graphs, Edges & Nodes - Untangling the Social Web
Partner Recruitment Webinar: "Join the Most Productive Ecosystem in Big Data ...
Java development with MongoDB
Designing and Building a Graph Database Application – Architectural Choices, ...
Concurrency Patterns with MongoDB
JSON-LD and MongoDB
Introduction to Graph Databases
Node.js vs Play Framework
Webinar: 10-Step Guide to Creating a Single View of your Business
Neo4j - 5 cool graph examples
Data Modeling with Neo4j
Ad

Similar to Webinar: MongoDB Persistence with Java and Morphia (20)

PPTX
Mongo sf easy java persistence
PPTX
Webinar: Simplifying Persistence for Java and MongoDB
PPTX
Webinar: Strongly Typed Languages and Flexible Schemas
PDF
Strongly Typed Languages and Flexible Schemas
PDF
A Spring Data’s Guide to Persistence
PPTX
MongoDB + Spring
PPTX
MongoDB and Spring - Two leaves of a same tree
PDF
No sql databases blrdroid devfest 2016
PPTX
ExSchema
PDF
Webinar: Building Your First App with MongoDB and Java
PDF
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
PDF
Painless Persistence in a Disconnected World
PPTX
ObjectBox - The new Mobile Database
PPTX
Java Persistence Frameworks for MongoDB
PDF
Javantura v2 - Morphia - painfree JPA for MongoDB - Philipp Krenn
PPT
Java Development with MongoDB (James Williams)
PPTX
Morphia, Spring Data & Co.
PDF
MongodB Internals
PPTX
Realm or: How I learned to stop worrying and love my app database
PDF
Data access 2.0? Please welcome: Spring Data!
Mongo sf easy java persistence
Webinar: Simplifying Persistence for Java and MongoDB
Webinar: Strongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible Schemas
A Spring Data’s Guide to Persistence
MongoDB + Spring
MongoDB and Spring - Two leaves of a same tree
No sql databases blrdroid devfest 2016
ExSchema
Webinar: Building Your First App with MongoDB and Java
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Painless Persistence in a Disconnected World
ObjectBox - The new Mobile Database
Java Persistence Frameworks for MongoDB
Javantura v2 - Morphia - painfree JPA for MongoDB - Philipp Krenn
Java Development with MongoDB (James Williams)
Morphia, Spring Data & Co.
MongodB Internals
Realm or: How I learned to stop worrying and love my app database
Data access 2.0? Please welcome: Spring Data!
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Approach and Philosophy of On baking technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
KodekX | Application Modernization Development
PDF
Modernizing your data center with Dell and AMD
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Mobile App Security Testing_ A Comprehensive Guide.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation_ Review paper, used for researhc scholars
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
20250228 LYD VKU AI Blended-Learning.pptx
Understanding_Digital_Forensics_Presentation.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Machine learning based COVID-19 study performance prediction
Approach and Philosophy of On baking technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KodekX | Application Modernization Development
Modernizing your data center with Dell and AMD
“AI and Expert System Decision Support & Business Intelligence Systems”

Webinar: MongoDB Persistence with Java and Morphia

  • 1. MongoDB Persistence with Java and Morphia Justin Lee Software Engineer, MongoDB
  • 3. What is Morphia? • Object document mapper — https://github.com/mongodb/morphia • Provides mapping to/from Java objects to mongodb • Annotation-based • Embedded objects/documents • References (lazy or eager) • Fluent query/update APIs • Runtime validation
  • 4. Why Morphia? • Offload object marshaling • automatically keeps up as objects evolve: new, removed, renamed • Higher abstraction • Simplified management of indexes • Unify code with schema management • Object/Document Versioning
  • 5. A Brief History • Created by Scott Hernandez • Hired by 10Gen —> started working on the kernel • Morphia left alone for a couple of years • Lots of uncertainty • James Green forked morphia • I was hired in June, 2013 in part to pick up Morphia • 5 releases since with another pending
  • 7. Adding morphia — Maven <dependency> <groupId>org.mongodb.morphia</groupId> <artifactId>morphia</artifactId> <version>0.105</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.11.3</version> </dependency>
  • 8. Adding morphia — Gradle compile "org.mongodb.morphia:morphia:0.105" compile "org.mongodb:mongo-java-driver:2.11.3" ! !
  • 9. Initializing morphia Morphia morphia = new Morphia(); Datastore datastore = morphia.createDatastore( new MongoClient(), “morphia-demo"); morphia.mapPackage("org.mongodb.morphia.demo"); datastore.ensureIndexes(); !
  • 11. Basic Entity @Entity public class GithubUser { private String userName; private String fullName; ! private Date memberSince; }
  • 12. Basic Entity @Entity (value = “users") public class GithubUser { private String userName; private String fullName; ! private Date memberSince; }
  • 13. Basic Entity @Entity (value = "users", noClassnameStored = true) public class GithubUser { private String userName; private String fullName; ! private Date memberSince; }
  • 14. Basic Entity @Entity (value = "users", noClassnameStored = true) public class GithubUser { @Id private String userName; private String fullName; ! private Date memberSince; }
  • 15. Basic Entity @Entity (value = "users", noClassnameStored = true) public class GithubUser { @Id private String userName; private String fullName; ! } @Property("since") private Date memberSince;
  • 16. Basic Entity — Saving GithubUser user = new GithubUser("evanchooly"); user.fullName = "Justin Lee"; user.memberSince = sdf.parse("6-15-1987"); datastore.save(user);
  • 17. Basic Entity — Shell repl0:PRIMARY> db.users.findOne() { "_id" : "evanchooly", "fullName" : "Justin Lee", "since" : ISODate("1987-06-15T04:00:00Z") }
  • 18. Complex Entities @Entity("orgs") public class Organization { @Id public String name; ! } public Organization(final String name) { this.name = name; }
  • 19. Complex Entities @Embedded public class Settings { public String defaultBranch = "master"; public Boolean allowWiki = false; public Boolean allowIssues = true; }
  • 20. Complex Entities @Entity("repos") public class Repository { @Id public String name; @Reference public Organization organization; @Reference public GithubUser owner; public Settings settings = new Settings(); }
  • 21. Complex Entities @Entity(value = "users", noClassnameStored = true) public class GithubUser { @Id public final String userName; public String fullName; @Property("since") public Date memberSince; @Reference(lazy = true) public List<Repository> repositories = new ArrayList<>(); }
  • 22. Complex Entities Organization org = new Organization("mongodb"); ! GithubUser user = new GithubUser("evanchooly"); user.fullName = "Justin Lee"; user.memberSince = sdf.parse("6-15-1987"); ! datastore.save(org); datastore.save(user); ! datastore.save(new Repository(org, "morphia")); datastore.save(new Repository(user, "morphia"));
  • 23. Complex Entities — Shell repl0:PRIMARY> show collections orgs repos system.indexes users
  • 24. Complex Entities — Shell repl0:PRIMARY> db.orgs.findOne(); { "_id" : "mongodb", "className" : "org.mongodb.morphia.demo.Organization" }
  • 25. Complex Entities — Shell repl0:PRIMARY> db.repos.find().pretty(); { "_id" : "mongodb/morphia", "className" : "org.mongodb.morphia.demo.Repository", "organization" : DBRef("orgs", "mongodb"), "settings" : { "defaultBranch" : "master", "allowWiki" : false, "allowIssues" : true } } { "_id" : "evanchooly/morphia", "className" : "org.mongodb.morphia.demo.Repository", "owner" : DBRef("users", "evanchooly"), "settings" : { … } }
  • 26. Complex Entities — Shell repl0:PRIMARY> db.users.findOne(); { "_id" : "evanchooly", "fullName" : "Justin Lee", "since" : ISODate("1987-06-15T04:00:00Z"), "repositories" : [ DBRef("repos", "mongodb/morphia"), DBRef("repos", "evanchooly/morphia") ] }
  • 28. Basic Query Query<Repository> query = datastore.createQuery(Repository.class); Repository repository = query.get(); ! runQuery called morphia-demo.repos {} ! List<Repository> repositories = query.asList(); ! runQuery called morphia-demo.repos {} ! Iterable<Repository> fetch = query.fetch(); ! … ?
  • 29. Basic Query Query<Repository> query = datastore.createQuery(Repository.class); query.field("owner").equal(evanchooly).get(); ! runQuery called morphia-demo.repos { owner: { $ref: "users", $id: "evanchooly" } }
  • 30. Complex Entities @Entity("repos") public class Repository { @Id public String name; @Reference public Organization organization; @Reference public GithubUser owner; public Settings settings = new Settings(); }
  • 31. Basic Query — @Property @Entity(value = "users", noClassnameStored = true) public class GithubUser { @Id private String userName; private String fullName; @Property("since") private Date memberSince; }
  • 32. Basic Query — @Property datastore.createQuery(GithubUser.class) .field("memberSince").equal(date).get(); ! GithubUser{userName='evanchooly', fullName='Justin Lee', memberSince=Mon Jun 15 00:00:00 EDT 1987} ! datastore.createQuery(GithubUser.class) .field("since").equal(date).get(); ! GithubUser{userName='evanchooly', fullName='Justin Lee', memberSince=Mon Jun 15 00:00:00 EDT 1987}
  • 34. Updating Entities evanchooly.followers = 12; datastore.save(evanchooly);
  • 35. Multiple Updates UpdateOperations<GithubUser> update = datastore.createUpdateOperations( GithubUser.class) .inc("followers").set("following", 42); Query<GithubUser> query = datastore.createQuery(GithubUser.class) .field(“followers”) .equal(0); datastore.update(query, update); ! update morphia-demo.users query: { followers: 0 } update: { $set: { following: 42 }, $inc: { followers: 1 } }
  • 36. Versioned Updates @Entity("orgs") public class Organization { @Id public String name; @Indexed public Date created; @Version(“v”) private long version; ! … ! }
  • 37. Versioned Updates Organization organization = datastore.createQuery(Organization.class).get(); Organization organization2 = datastore.createQuery(Organization.class).get(); ! datastore.save(organization); // fine datastore.save(organization); // fine datastore.save(organization2); ! java.util.ConcurrentModificationException: Entity of class org.mongodb.morphia.demo.Organization (id='mongodb',version='1') was concurrently updated.
  • 39. Indexes — Fields @Entity("orgs") public class Organization { @Id public String name; @Indexed(value = IndexDirection.ASC, unique = false, name = "", dropDups = false, background = false, sparse = false, expireAfterSeconds = -1) public Date created; ! … }
  • 40. Indexes — Fields repl0:PRIMARY> db.orgs.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "morphia-demo.orgs" }, { "v" : 1, "key" : { "created" : 1 }, "name" : "created_1", "ns" : "morphia-demo.orgs" } ]
  • 41. Indexes — Classes @Entity(value = "users", noClassnameStored = true) @Indexes({ @Index(value ="userName, -followers", name = "popular") }) public class GithubUser { @Id public String userName; public String fullName; @Property("since") public Date memberSince; public Date lastActive; @Reference(lazy = true) public List<Repository> repositories = new ArrayList<>(); public int followers = 0; public int following = 0; ! …
  • 43. The Road to 1.0 • It’s short • Aggregation support • Text Searching • Improved geo support • Handful of bug fixes
  • 44. Resources • Morphia Homepage https://github.com/mongodb/morphia • Discussions Forum https://groups.google.com/forum/#!forum/ morphia • This presentation and code https://github.com/evanchooly/morphiademo
  • 46. MongoDB Persistence with Java and Morphia Justin Lee Software Engineer, MongoDB