SlideShare a Scribd company logo
Java Day Charkiv
Painfree Object-
Document Mapping
for MongoDB
Philipp Krenn @xeraa
Vienna
Vienna
Vienna
ViennaDB
Papers We Love Vienna
Electronic Data Interchange (EDI)
Who uses
JPA?
Who uses
MongoDB?
Who has heard of
Morphia?
Like JPA for
MongoDB
...but better
@OneToMany(mappedBy = "destCustomerId")
@ManyToMany
@Fetch(FetchMode.SUBSELECT)
@JoinTable(name = "customer_dealer_map",
joinColumns = {
@JoinColumn(name = "customer_id",
referencedColumnName = "id")},
inverseJoinColumns = {
@JoinColumn(name = "dealer_id",
referencedColumnName = "id")})
private Collection<Client> dealers;
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Relations vs Objects
Ted Neward: ORM is
"The Vietnam of
Computer Science"
http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx
MongoDB
Table = Collection
Schemaless
Row = Document
JSON
{
"name": "Philipp",
"isAlive": true,
"age": 30,
"height_cm": 181.5,
"address": {
"city": "Vienna",
"postalCode": "1190"
},
"phoneNumbers": [ {
"type": "mobile",
"number": "+43 123 4567890"
} ]
}
MongoDB Java driver
List<BasicDBObject> phoneNumbers = new ArrayList<>();
phoneNumbers.add(
new BasicDBObject("type", "mobile")
.append("number", "+43 123 4567890"));
BasicDBObject document = new BasicDBObject("name", "Philipp")
.append("isAlive", true)
.append("age", 30)
.append("height_cm", 181.5f)
.append("address",
new BasicDBObject("city", "Vienna")
.append("postalCode", "1190"))
.append("phoneNumbers", phoneNumbers);
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Morphia
Object-Document
Mapping
POJO + Annotations
Object-Relational Mapping
Features
Lightweight
Type safe & preserving
Required libraries
https://github.com/mongodb/
mongo-java-driver (3.0.4)
+
https://github.com/mongodb/
morphia (1.0.1)
Show me some code
https://github.com/xeraa/
morphia-demo
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
$ gradle test
Standalone or embedded
MongoDB
Annotations
Collections
@Entity(
value = "company"
)
public class CompanyEntity {
@Id
protected ObjectId id;
public CompanyEntity() { }
Do not
use dashes in the collection name
https://www.destroyallsoftware.com/talks/wat
Do not
copy paste the value attribute
Do not
use @Id as String (without reason)
Polymorphism
public abstract class EmployeeEntity {
protected String name;
}
public class ManagerEntity extends EmployeeEntity {
protected Boolean approveFunds;
}
public class WorkerEntity extends EmployeeEntity {
protected Integer yearsExperience;
}
RDBMS
1. Union table with (many) NULL
values
RDBMS
2. Concrete instances without
common queries
RDBMS
3. Base table joined with all
subtables
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
@Entity(value = "employee", noClassnameStored = false)
public abstract class EmployeeEntity {
@Id
protected ObjectId id;
protected String name;
}
public class ManagerEntity extends EmployeeEntity {
protected Boolean approveFunds;
}
public class WorkerEntity extends EmployeeEntity {
protected Integer yearsExperience;
}
{
"_id": ObjectId("5461c8bf9e2acf32ed50c079"),
"className": "net.xeraa.morphia_demo.entities.ManagerEntity",
"name": "Peter",
"approveFunds": true
}
{
"_id": ObjectId("524d9fe7e4b0f8bd3031f84e"),
"className": "net.xeraa.morphia_demo.entities.WorkerEntity",
"name": "Philipp",
"yearsExperience": 10
}
className and refactoring?
Properties
protected String firstname;
@AlsoLoad("lastname")
protected String surname;
protected Boolean approveFunds;
@Property("hire")
protected boolean managerCanApproveHires;
public EmployeeEntity setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
Do
trim property names (MMAPv1)
Do
use object data types
Do
provide chainable setters
Do
Or use Lombok !
Indexes
@Entity(value = "employee", noClassnameStored = false)
@Indexes(@Index(name = "name", fields = {
@Field(value = "surname"),
@Field(value = "firstname")
}))
public class EmployeeEntity {
protected String firstname;
protected String surname;
@Indexed(unique = true, sparse = false)
protected String email;
Optimistic locking
vs pessimistic locking in RDBMS
@Version
private long version;
{
...
"version": NumberLong("1")
}
Anti JOIN
public class EmployeeEntity {
@Reference
protected CompanyEntity company;
@Embedded
protected BankConnectionEntity bankConnection;
Queries
Save or upsert
public ObjectId persistCompanyEntity(CompanyEntity company) {
mongoDatastore.save(company);
return company.getId();
}
public ObjectId persistManagerEntity(ManagerEntity manager) {
mongoDatastore.save(manager);
return manager.getId();
}
public ObjectId persistWorkerEntity(WorkerEntity worker) {
mongoDatastore.save(worker);
return worker.getId();
}
Get data
public EmployeeEntity findByEmail(final String email) {
return mongoDatastore.find(EmployeeEntity.class)
.field("email").equal(email).get();
}
public List<EmployeeEntity> getAllEmployees() {
return mongoDatastore.find(EmployeeEntity.class).asList();
}
public List<ManagerEntity> getAllManagers() {
return mongoDatastore.find(ManagerEntity.class)
.disableValidation()
.field("className").equal(ManagerEntity.class.getName())
.asList();
}
Watch out
.equal() != .equals()
Trust your compiler
Performance
Normalize fields
email.toLowerCase() before saving
More queries
Regular expressions
.exists(), .doesNotExist()
.greaterThan(), .hasAnyOf(),...
.sort(), .skip(), .limit()
More features
Capped collections
GridFS
Aggregation framework
Geo locations
Patterns
Base Class
public abstract class BaseEntity {
@Id
protected ObjectId id;
protected Date creationDate;
protected Date lastChange;
@Version
private long version;
public BaseEntity() {
super();
}
// No setters
public ObjectId getId() {
return id;
}
public Date getCreationDate() {
return creationDate;
}
public Date getLastChange() {
return lastChange;
}
@PrePersist
public void prePersist() {
this.creationDate =
(creationDate == null) ? new Date() : creationDate;
this.lastChange =
(lastChange == null) ? creationDate : new Date();
}
public abstract String toString();
}
public <E extends BaseEntity> ObjectId persist(E entity) {
mongoDatastore.save(entity);
return entity.getId();
}
public <E extends BaseEntity> long count(Class<E> clazz) {
return mongoDatastore.find(clazz).countAll();
}
public <E extends BaseEntity> E get(Class<E> clazz, final ObjectId id) {
return mongoDatastore.find(clazz).field("id").equal(id).get();
}
Converters
Option 1
Not readable or searchable in the database
@Serialized
protected BigDecimal bonus;
Option 2
Fugly
@Transient
protected BigDecimal salary;
protected String salaryString;
@PrePersist
public void prePersist() {
super.prePersist();
if (salary != null) {
this.salaryString = this.salary.toString();
}
}
@PostLoad
public void postLoad() {
if (salaryString != null) {
this.salary = new BigDecimal(salaryString);
} else {
this.salary = null;
}
}
Option 3
Yes!
@Converters({BigDecimalConverter.class})
public class WorkerEntity extends EmployeeEntity {
protected BigDecimal dailyAllowance;
public class BigDecimalConverter extends TypeConverter implements SimpleValueConverter {
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
if (value == null) {
return null;
}
return value.toString();
}
@Override
public Object decode(Class targetClass, Object fromDBObject,
MappedField optionalExtraInfo) throws MappingException {
if (fromDBObject == null) {
return null;
}
return new BigDecimal(fromDBObject.toString());
}
}
More
http://projects.spring.io/spring-data-mongodb/
https://github.com/fakemongo/fongo
https://github.com/evanchooly/critter
Critter
Query<Query> query = ds.createQuery(Query.class);
query.and(
query.criteria("bookmark").equal(bookmark),
query.criteria("database").equal(database)
);
QueryCriteria criteria = new QueryCriteria(datastore);
criteria.and(
criteria.bookmark(bookmark),
criteria.database(database)
);
Query query = criteria.query().get();
But is it fast?
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Conclusion
Things you won't get
Transactions
JOINs
Things you will get
Rapid development
Easy replication and sharding
Impedence match with rich
documents
To sum up
Developers ❤ Morphia
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Thanks!
Questions?
@xeraa
Image Credit
• Schnitzel https://flic.kr/p/9m27wm
• Architecture https://flic.kr/p/6dwCAe
• Conchita https://flic.kr/p/nBqSHT
• Paper: http://www.freeimages.com/photo/432276

More Related Content

PDF
An introduction into Spring Data
PDF
Ajax chap 4
PDF
Ajax chap 5
PPTX
NoSQL Endgame JCON Conference 2020
PDF
Devoxx08 - Nuxeo Core, JCR 2, CMIS
PDF
Ajax chap 2.-part 1
PDF
Ajax chap 3
KEY
SOLID Principles
An introduction into Spring Data
Ajax chap 4
Ajax chap 5
NoSQL Endgame JCON Conference 2020
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Ajax chap 2.-part 1
Ajax chap 3
SOLID Principles

What's hot (19)

PPTX
Spring framework part 2
PDF
Di web tech mail (no subject)
PDF
Wed 1630 greene_robert_color
PDF
Cloud computing BI publication 1
PDF
Windows 8 Training Fundamental - 1
KEY
The Principle of Hybrid App.
PPTX
NoSQL Endgame Percona Live Online 2020
PDF
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
PPTX
java API for XML DOM
KEY
MongoDB and PHP ZendCon 2011
ODP
Modularized Persistence - B Zsoldos
PPTX
Jasig Cas High Availability - Yale University
KEY
MongoDB, PHP and the cloud - php cloud summit 2011
PDF
Mattbrenner
PDF
How to write bad code in redux (ReactNext 2018)
PDF
MongoDB .local Munich 2019: Best Practices for Working with IoT and Time-seri...
PDF
09.Local Database Files and Storage on WP
PDF
Di and Dagger
PDF
Softshake - Offline applications
Spring framework part 2
Di web tech mail (no subject)
Wed 1630 greene_robert_color
Cloud computing BI publication 1
Windows 8 Training Fundamental - 1
The Principle of Hybrid App.
NoSQL Endgame Percona Live Online 2020
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
java API for XML DOM
MongoDB and PHP ZendCon 2011
Modularized Persistence - B Zsoldos
Jasig Cas High Availability - Yale University
MongoDB, PHP and the cloud - php cloud summit 2011
Mattbrenner
How to write bad code in redux (ReactNext 2018)
MongoDB .local Munich 2019: Best Practices for Working with IoT and Time-seri...
09.Local Database Files and Storage on WP
Di and Dagger
Softshake - Offline applications
Ad

Similar to Paintfree Object-Document Mapping for MongoDB by Philipp Krenn (20)

PDF
A Spring Data’s Guide to Persistence
PDF
Webinar: MongoDB Persistence with Java and Morphia
PDF
Joker'15 Java straitjackets for MongoDB
PPTX
Benefits of Using MongoDB Over RDBMSs
PDF
MongodB Internals
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PDF
Refactoring to Java 8 (Devoxx BE)
PPTX
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
PDF
NDC London 2013 - Mongo db for c# developers
PPTX
Mongo sf easy java persistence
PPTX
MongoDB: Easy Java Persistence with Morphia
PPTX
Webinar: What's new in the .NET Driver
PDF
Inside Gorm
PPT
PDF
Java on Google App engine
PPTX
MongoDB + Spring
PPTX
MongoDB and Spring - Two leaves of a same tree
ODP
Java Persistence API
PDF
Webinar: Building Your First App with MongoDB and Java
PPTX
Transitioning from SQL to MongoDB
A Spring Data’s Guide to Persistence
Webinar: MongoDB Persistence with Java and Morphia
Joker'15 Java straitjackets for MongoDB
Benefits of Using MongoDB Over RDBMSs
MongodB Internals
Morphia: Simplifying Persistence for Java and MongoDB
Refactoring to Java 8 (Devoxx BE)
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
NDC London 2013 - Mongo db for c# developers
Mongo sf easy java persistence
MongoDB: Easy Java Persistence with Morphia
Webinar: What's new in the .NET Driver
Inside Gorm
Java on Google App engine
MongoDB + Spring
MongoDB and Spring - Two leaves of a same tree
Java Persistence API
Webinar: Building Your First App with MongoDB and Java
Transitioning from SQL to MongoDB
Ad

More from JavaDayUA (20)

PDF
STEMing Kids: One workshop at a time
PDF
Flavors of Concurrency in Java
PDF
What to expect from Java 9
PDF
Continuously building, releasing and deploying software: The Revenge of the M...
PDF
The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
PDF
20 Years of Java
PDF
How to get the most out of code reviews
PDF
Unlocking the Magic of Monads with Java 8
PDF
Virtual Private Cloud with container technologies for DevOps
PPTX
JShell: An Interactive Shell for the Java Platform
PPTX
Interactive Java Support to your tool -- The JShell API and Architecture
PDF
MapDB - taking Java collections to the next level
PDF
Save Java memory
PDF
Design rationales in the JRockit JVM
PPTX
Next-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
PPTX
Apache Cassandra. Inception - all you need to know by Mikhail Dubkov
PPTX
Solution Architecture tips & tricks by Roman Shramkov
PPTX
Testing in Legacy: from Rags to Riches by Taras Slipets
PDF
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
PDF
Spark-driven audience counting by Boris Trofimov
STEMing Kids: One workshop at a time
Flavors of Concurrency in Java
What to expect from Java 9
Continuously building, releasing and deploying software: The Revenge of the M...
The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
20 Years of Java
How to get the most out of code reviews
Unlocking the Magic of Monads with Java 8
Virtual Private Cloud with container technologies for DevOps
JShell: An Interactive Shell for the Java Platform
Interactive Java Support to your tool -- The JShell API and Architecture
MapDB - taking Java collections to the next level
Save Java memory
Design rationales in the JRockit JVM
Next-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
Apache Cassandra. Inception - all you need to know by Mikhail Dubkov
Solution Architecture tips & tricks by Roman Shramkov
Testing in Legacy: from Rags to Riches by Taras Slipets
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
Spark-driven audience counting by Boris Trofimov

Recently uploaded (20)

PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
1. Introduction to Computer Programming.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Machine Learning_overview_presentation.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Mushroom cultivation and it's methods.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Heart disease approach using modified random forest and particle swarm optimi...
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
Getting Started with Data Integration: FME Form 101
1. Introduction to Computer Programming.pptx
Encapsulation theory and applications.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Empathic Computing: Creating Shared Understanding
A comparative study of natural language inference in Swahili using monolingua...
Spectral efficient network and resource selection model in 5G networks
SOPHOS-XG Firewall Administrator PPT.pptx
Encapsulation_ Review paper, used for researhc scholars
Machine Learning_overview_presentation.pptx
cloud_computing_Infrastucture_as_cloud_p
Mushroom cultivation and it's methods.pdf
NewMind AI Weekly Chronicles - August'25-Week II
A comparative analysis of optical character recognition models for extracting...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Paintfree Object-Document Mapping for MongoDB by Philipp Krenn