Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Painfree Object-Document Mapping for MongoDB by...
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Riga Dev Day
March 13, 2016
46
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Painfree Object-Document Mapping for MongoDB by Philipp Krenn
Riga Dev Day
March 13, 2016
More Decks by Riga Dev Day
See All by Riga Dev Day
Faster Java by Adding Structs (Sort Of)
rigadevday
0
180
Prepare for JDK 9! by Dalibor Topic
rigadevday
0
150
Little Important Things in Distributed Architectures by Andres Jaan Tack
rigadevday
0
150
Oracle 12c for Developers by Alex Nuijten
rigadevday
1
150
The Language of Regular Expressions. So You Think You Can Speak It? by Rustam Mehmandarov
rigadevday
0
92
Modern Java Component Design with Spring 4.3 by Juergen Hoeller
rigadevday
0
280
Open Source and OpenJDK: Do They Deliver? by Simon Ritter
rigadevday
0
82
Google Apps Integration in Oracle Apex by Richard Martens
rigadevday
0
310
Integration Testing from the Trenches by Nicolas Fränkel
rigadevday
0
250
Featured
See All Featured
Money Talks: Using Revenue to Get Sh*t Done
nikkihalliwell
0
550
職位にかかわらず全員がリーダーシップを発揮するチーム作り / Building a team where everyone can demonstrate leadership regardless of position
madoxten
70
68k
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.8k
Building a Modern Day E-commerce SEO Strategy
aleyda
45
9.3k
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
1
600
Building Flexible Design Systems
yeseniaperezcruz
330
41k
Why You Should Never Use an ORM
jnunemaker
PRO
61
10k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
287
14k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
920
Java REST API Framework Comparison - PWX 2021
mraible
34
9.8k
We Analyzed 250 Million AI Search Results: Here's What I Found
joshbly
2
2.1k
How to build an LLM SEO readiness audit: a practical framework
nmsamuel
2
970
Transcript
RigaDevDay 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;
None
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);
None
None
Morphia
Object-Document Mapping POJO + Annotations Object-Relational Mapping
Features Lightweight Type safe & preserving
Required libraries https://github.com/mongodb/ mongo-java-driver (3.2.2) + https://github.com/mongodb/ morphia (1.1.1)
Show me some code https://github.com/xeraa/ morphia-demo
None
$ 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
None
@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 use Lombok for more !
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 Full-text search 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?
None
Conclusion
Things you won't get Transactions JOINs
Things you will get Rapid development Replication and sharding Impedence
match with rich documents
To sum up Developers ❤ Morphia
None
PS: Elastic
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