SlideShare a Scribd company logo
codecentric AG 1
Morphia, Spring Data & Co. -
Java Persistenz-Frameworks für MongoDB
Tobias.Trelle@codecentric.de @tobiastrelle
codecentric AG 2
Tobias Trelle
- Senior IT Consultant @
codecentric AG (Düsseldorf)
- Organisator MongoDB
Usergruppe Düsseldorf
- Autor MongoDB-Buch
(dpunkt-Verlag)
codecentric AG 3
Where have all my tables gone …
ORM is dead
long live ODM
codecentric AG 4
MongoDB?
 NoSQL-Datenbank / Open Source
 Dokumentenorientiert
 Hochperformant, horizontal skalierbar (scale-out)
 Replication & Sharding out-of-the-box
 Map/Reduce
 Geospatial Indexes / Queries
codecentric AG 5
Grundkonzept MongoDB-Server
Server
Database
Collection
Document
Field
Tabelle
Zeile
Spalte
Relationales
Pendant Aber …
Flexibles
Schema
- Arrays
- Rekursiv
codecentric AG 6
Document
{
title: „Praxisbuch Mongo“,
version: 0.1,
copies_sold: 0,
authors: [
{ name: „Uwe Seiler“,
email: „uwe.seiler@codecentric.de“ },
{ name: „Tobias Trelle“,
email: „tobias.trelle@codecentric.de“}
]
}
codecentric AG 7
JSON vs. BSON
{ hello: "MongoDB" }
x18x00x00x00
x02
hellox00
x08x00x00x00MongoDBx00
x00
codecentric AG 8
CRUD = IFUR
insert(…)
find(…), findOne(…)
update(…)
remove()
codecentric AG 9
Java Persistenz mit MongoDB
MongoDB Java Driver
Spring Data MongoDB
Morphia
Hibernate OGM
Jongo
codecentric AG 10
Use Case
db.order.find( {"items.quantity": ? } )
codecentric AG 11
Mongo Java Driver
codecentric AG 12
MongoDB Drivers
 One wire protocol for all client languages
 A driver implementation per language
 Responsibilities:
 Converting language dependent data structures   BSON
 Generating ObjectId for _id field
 Overview: http://www.mongodb.org/display/DOCS/Drivers
codecentric AG 13
MongoDB Java Driver
One JAR w/o further dependencies:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.3</version>
</dependency>
github:
https://github.com/mongodb/mongo-java-driver
codecentric AG 14
Java Driver: Connect to MongoDB
import com.mongodb.MongoClient;
// Default: localhost:27017
mongo = new MongoClient();
// Sharding: mongos server
mongo = new MongoClient("mongos01", 4711);
// Replica set
mongo = new MongoClient(Arrays.asList(
new ServerAddress("replicant01", 10001),
new ServerAddress("replicant02", 10002),
new ServerAddress("replicant03", 10003)
));
codecentric AG 15
Java Driver: Database / Collection
import com.mongodb.DB;
import com.mongodb.DBCollection;
DB db = mongo.getDB("test");
DBCollection collection =
db.getCollection("foo");
codecentric AG 16
Java Driver: Documents
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
// insert document
DBObject doc = new BasicDBObject();
doc.put("date", new Date());
doc.put("i", 42);
collection.insert(doc);
codecentric AG 17
Java Driver: Queries
import com.mongodb.DBCursor;
DBCursor cursor;
cursor = collection.find(); // all documents
// documents w/ {i: 42}
cursor = collection.find(
new BasicDBObject("i", 42) );
document = cursor.next();
...
codecentric AG 18
Java Driver: Order Use Case
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("order");
DBObject order;
List<DBObject> items = new ArrayList<DBObject>();
DBObject item;
// order
order = new BasicDBObject();
order.put("date", new Date());
order.put("custInfo" , "Tobias Trelle");
order.put("items", items);
// items
item = new BasicDBObject();
item.put("quantity", 1);
item.put("price", 47.11);
item.put("desc", "Item #1");
items.add(item);
item = new BasicDBObject();
item.put("quantity", 2);
item.put("price", 42.0);
item.put("desc", "Item #2");
items.add(item);
collection.insert(order);
codecentric AG 19
Java Driver: Order Use Case
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection("order");
DBObject query;
DBObject document;
DBCursor cursor;
query = new BasicDBObject("items.quantity", 2);
cursor = collection.find(query);
while ( cursor.hasNext() ) {
document = cursor.next();
println(document);
}
codecentric AG 20
Spring Data
MongoDB
codecentric AG 21
Spring Data MongoDB – Fact Sheet
Vendor VMware / SpringSource
License Apache License, Version 2.0
Documentation http://www.springsource.org/spring-data/mongodb
Main Features • Repository Support
• Object/Document Mapping
• Templating
codecentric AG 22
Spring Data
Common patterns for RDBMS and NoSQL data stores
Spring Data
RDBMS MongoDB Neo4j …
Spring Data
JPA
CrudRepository PagingAndSortingRepository
JpaRepository
JPA
JDBC
Spring Data
MongoDB
MongoRepository
MongoTemplate
Spring Data
Neo4j
Spring Data
…
GraphRepository
Neo4jTemplate
Mongo Java Driver
Embedded REST
Quelle: http://www.infoq.com/articles/spring-data-intro
codecentric AG 23
Spring Data MongoDB
Templating
 Resource abstraction
 Configure connections to mongod / mongos node(s)
 Collection lifecycle ( create, drop)
 Map/Reduce / Aggregation
Object Mapping
 Annotation based: @Document, @Field, @Index etc.
 Classes are mapped to collections, Java Objects to documents
Repository Support
 Queries are derived from methods signatures
 Annotated Queries
codecentric AG 24
Spring Data MongoDB: Configuration
<!-- Connection to MongoDB server -->
<mongo:db-factory host="localhost" port="27017" dbname="test" />
<!-- MongoDB Template -->
<bean id="mongoTemplate„
class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<!-- Package w/ automagic repositories -->
<mongo:repositories base-package="mongodb" />
codecentric AG 26
Spring Data MongoDB: Object Mapping
public class Order {
@Id private String id;
private Date date;
@Field("custInfo") private String customerInfo;
List<Item> items; ...
}
public class Item {
private int quantity;
private double price;
@Field("desc") private String description;
...
}
codecentric AG 27
Spring Data MongoDB: Repository Support
public interface OrderRepository extends
MongoRepository<Order, String> {
List<Order> findByItemsQuantity(int quantity);
@Query("{ "items.quantity": ?0 }")
List<Order> findWithQuery(int quantity);
}
codecentric AG 28
Spring Data MongoDB: Additional Goodies
 Map/Reduce / Aggregation framework
 Index Management
 Support for GridFS
 Geopspatial indexes / queries
 Optimistic Locking
codecentric AG 29
Hibernate OGM
codecentric AG 30
Hibernate OGM MongoDB – Fact Sheet
Vendor JBoss / Redhat
License GNU LGPL, Version 2.1
Documentation http://www.hibernate.org/subprojects/ogm.html
Main Features • JPA API (Subset)
• JPQL Query Language
codecentric AG 31
Hibernate OGM
 Implements JPA API (subset)
 JP-QL query are translated to native
datastore queries
 Supports Infinispan, EhCache, MongoDB
codecentric AG 32
Hibernate OGM
Architecture
Source:
http://docs.jboss.org/hibernate/ogm/4.0/reference/en-
US/html/ogm-architecture.html#d0e409
codecentric AG 33
Hibernate OGM MongoDB: Configuration
<persistence version="2.0" …>
<persistence-unit name="primary">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<class>hibernate.Order</class>
<class>hibernate.Item</class>
<properties>
<property name="hibernate.ogm.datastore.provider"
value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/>
<property name="hibernate.ogm.mongodb.database" value=„odm"/>
<property name="hibernate.ogm.mongodb.host" value=„localhost"/>
<property name="hibernate.ogm.mongodb.port" value=„27017"/>
</properties>
</persistence-unit>
</persistence>
codecentric AG 34
Hibernate OGM MongoDB: Object Mapping
@Entity
@NamedQuery(
name="byItemsQuantity",
query = "SELECT o FROM Order o JOIN o.items i WHERE i.quantity = :quantity"
)
public class Order {
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Id private String id;
private Date date;
@Column(name = "custInfo") private String customerInfo;
@ElementCollection
private List<Item> items;
codecentric AG 35
Hibernate OGM MongoDB: Object Mapping
@Embeddable
public class Item {
private int quantity;
private double price;
@Column(name="desc") private String description;
...
codecentric AG 36
Hibernate OGM: Summary
 Very early beta
 Only persist / merge / remove
 No query support (yet)
 Uses relational API
codecentric AG 37
Hibernate OGM: OgmEntityManager
codecentric AG 38
Morphia
codecentric AG 39
Morphia – Fact Sheet
Developer Scott Hernandez, James Green
License Apache License, Version 2.0
Documentation https://github.com/jmkgreen/morphia/wiki/Overview
Main Features • Object/Document Mapping
• Custom Query API
• DAO support
codecentric AG 40
Morphia: Object Mapping
public class Order {
@Id private ObjectId id;
private Date date;
@Property("custInfo") private String customerInfo;
@Embedded List<Item> items;
...
}
public class Item {
private int quantity;
private double price;
@Property("desc") private String description;
...
}
codecentric AG 41
Morphia: Queries
public class OrderDao extends BasicDAO<Order, ObjectId> {
List<Order> findByItemsQuantity(int quantity) {
return
find( createQuery().filter("items.quantity", quantity))
.asList();
}
List<Order> findByItemsPriceGreaterThan(double price) {
return
find( createQuery().field("items.price").greaterThan(price) )
.asList();
}
…
}
codecentric AG 42
Morphia: Custom query syntax – why?
Morphia Mongo Query
= $eq
!=, <> $neq
>, <, >=,<= $gt, $lt, $gte, $lte
in, nin $in, $nin
elem $elemMatch
… ….
codecentric AG 43
Jongo
codecentric AG 44
Jongo – Fact Sheet
Developer Benoît Guérout, Yves Amsellem
License Apache License, Version 2.0
Documentation http://jongo.org/
Main Features • Object/Document Mapping
• Custom Query API
codecentric AG 45
Jongo: Object Mapping
public class Order {
private ObjectId id;
private Date date;
@JsonProperty("custInfo") private String customerInfo;
List<Item> items;
… }
public class Item {
private int quantity;
private double price;
@JsonProperty("desc") private String description;
…
}
codecentric AG 46
Jongo: Queries
// Java driver API
MongoClient mc = new MongoClient();
DB db = mc.getDB("odm_jongo");
// Jongo API entry point
Jongo jongo = new Jongo(db);
MongoCollection orders = jongo.getCollection("order");
// no DAO needed
Iterable<Order> result =
orders.find("{"items.quantity": #}", 2).as(Order.class);
// supports projection
Iterable<X> result =
orders.find().fields("{_id:0, date:1, custInfo:1}").as(X.class);
codecentric AG 47
Judge yourself …
Spring Data MongoDB
https://github.com/ttrelle/spring-data-examples
Hibernate OGM MongoDB
https://github.com/ttrelle/hibernate-ogm-examples
Jongo
https://github.com/ttrelle/jongo-examples
Morphia
https://github.com/ttrelle/morphia-mongodb-examples
codecentric AG 48
Summary
ODM
Annotations
Queries
Java Driver -- Nested BasicDBObject‘s
Spring Data MongoDB Custom Interface w/
- derived queries
- JSON queries
Hibernate OGM JPA JPQL: @Named(Native)Query +
EntityManager
Jongo Jackson JSON queries via collection
wrapper
Morphia Custom BasicDAO super class w/ 2
flavours of fluent API
codecentric AG 49
Which one should I use?
Hibernate OGM
Spring Data
MongoDB
MongoDB Java Driver
Morphia
JPA
JDBC
MongoDB
Jongo
- Ready for production
- Supported by 10gen
Mature
- Ready for production
- Active community
-Too early to judge
- API mismatch
The „better“ driver
codecentric AG 50
MongoDB User Group Düsseldorf
https://www.xing.com/net/mongodb-dus
@MongoDUS
MUG Düsseldorf
codecentric AG 51
QUESTIONS?
Tobias Trelle
codecentric AG
Merscheider Str. 1
42699 Solingen
tel +49 (0) 212.233628.47
fax +49 (0) 212.233628.79
mail Tobias.Trelle@codecentric.de
twitter @tobiastrelle
www.codecentric.de
blog.codecentric.de/en/author/tobias-trelle
www.xing.com/net/mongodb-dus

More Related Content

What's hot (19)

PPTX
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
PPTX
Java Development with MongoDB
Scott Hernandez
 
PPTX
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
PPTX
MongoDB + Java - Everything you need to know
Norberto Leite
 
PPTX
Building Spring Data with MongoDB
MongoDB
 
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
PDF
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
PPTX
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
MongoDB
 
PPTX
Getting Started with MongoDB and NodeJS
MongoDB
 
PDF
MongoDB Performance Tuning
Puneet Behl
 
PPTX
Indexing Strategies to Help You Scale
MongoDB
 
PDF
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
PDF
An introduction to MongoDB
Universidade de São Paulo
 
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
KEY
Introduction to Restkit
petertmarks
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PDF
What do you mean, Backwards Compatibility?
Trisha Gee
 
PPT
Fast querying indexing for performance (4)
MongoDB
 
PPTX
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Java Development with MongoDB
Scott Hernandez
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
MongoDB + Java - Everything you need to know
Norberto Leite
 
Building Spring Data with MongoDB
MongoDB
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
Webinar: Building Your First App with MongoDB and Java
MongoDB
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
MongoDB
 
Getting Started with MongoDB and NodeJS
MongoDB
 
MongoDB Performance Tuning
Puneet Behl
 
Indexing Strategies to Help You Scale
MongoDB
 
Data access 2.0? Please welcome: Spring Data!
Oliver Gierke
 
An introduction to MongoDB
Universidade de São Paulo
 
Back to Basics Webinar 5: Introduction to the Aggregation Framework
MongoDB
 
Introduction to Restkit
petertmarks
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
What do you mean, Backwards Compatibility?
Trisha Gee
 
Fast querying indexing for performance (4)
MongoDB
 
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 

Viewers also liked (15)

KEY
The Spring Data MongoDB Project
MongoDB
 
PDF
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Kuo-Chun Su
 
PPTX
The Aggregation Framework
MongoDB
 
PPTX
MongoDB for Time Series Data Part 2: Analyzing Time Series Data Using the Agg...
MongoDB
 
PPTX
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB
 
PDF
Are You Ready to Cut The Cable?
Mkv Xstream
 
PDF
Port folio 20121005
Thành Mắm
 
PPTX
Happy-bday-reechal
Richa Vishnoi
 
PPT
Pautas
isdagana
 
PPT
Copy of shortckt
Senthil Kumar
 
PDF
Introducing Eaton Square
Nick Kelly
 
PPT
Сомниум Нетворк-Новая презентация!
onlinesarabotok
 
PDF
The Social Challenge of 1.5°C Webinar: Ilan Chabay
tewksjj
 
PPTX
Scaling wordpress for high traffic
Roshan Bhattarai
 
PDF
2 power and hydrogen generation figures
novi5036
 
The Spring Data MongoDB Project
MongoDB
 
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Kuo-Chun Su
 
The Aggregation Framework
MongoDB
 
MongoDB for Time Series Data Part 2: Analyzing Time Series Data Using the Agg...
MongoDB
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB
 
Are You Ready to Cut The Cable?
Mkv Xstream
 
Port folio 20121005
Thành Mắm
 
Happy-bday-reechal
Richa Vishnoi
 
Pautas
isdagana
 
Copy of shortckt
Senthil Kumar
 
Introducing Eaton Square
Nick Kelly
 
Сомниум Нетворк-Новая презентация!
onlinesarabotok
 
The Social Challenge of 1.5°C Webinar: Ilan Chabay
tewksjj
 
Scaling wordpress for high traffic
Roshan Bhattarai
 
2 power and hydrogen generation figures
novi5036
 
Ad

Similar to Morphia, Spring Data & Co. (20)

PDF
Building your first app with MongoDB
Norberto Leite
 
PPTX
Webinar: Building Your First App
MongoDB
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PDF
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
PPT
Java Development with MongoDB (James Williams)
MongoSF
 
PDF
Spring Data MongoDB 介紹
Kuo-Chun Su
 
PPTX
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
Narendranath Reddy
 
PDF
How to use MongoDB with CakePHP
ichikaway
 
PDF
Green dao
Droidcon Berlin
 
PPTX
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
PPTX
Dev Jumpstart: Building Your First App
MongoDB
 
PDF
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
PDF
full stack modul 5, mongodb,webpack,front-end,back-end
leapsky6
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
PDF
Mongo db eveningschemadesign
MongoDB APAC
 
PPTX
Webinar: Building Your First MongoDB App
MongoDB
 
PDF
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
PPTX
Introduction to MongoDB
Chun-Kai Wang
 
PPTX
Test Automation for NoSQL Databases
Tobias Trelle
 
Building your first app with MongoDB
Norberto Leite
 
Webinar: Building Your First App
MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
 
Java Development with MongoDB (James Williams)
MongoSF
 
Spring Data MongoDB 介紹
Kuo-Chun Su
 
Mongodb ExpressJS HandlebarsJS NodeJS FullStack
Narendranath Reddy
 
How to use MongoDB with CakePHP
ichikaway
 
Green dao
Droidcon Berlin
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Dev Jumpstart: Building Your First App
MongoDB
 
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
full stack modul 5, mongodb,webpack,front-end,back-end
leapsky6
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Mongo db eveningschemadesign
MongoDB APAC
 
Webinar: Building Your First MongoDB App
MongoDB
 
Back to Basics 2017: Mí primera aplicación MongoDB
MongoDB
 
Introduction to MongoDB
Chun-Kai Wang
 
Test Automation for NoSQL Databases
Tobias Trelle
 
Ad

More from Tobias Trelle (10)

PDF
TDD mit JUnit und Mockito
Tobias Trelle
 
PDF
NoSQL - Einführung in Graphen-Datenbanken mit Neo4j
Tobias Trelle
 
PPTX
Einführung in NoSQL-Datenbanken
Tobias Trelle
 
PPTX
MongoDB Einführung
Tobias Trelle
 
PDF
MongoDB - Riesige Datenmengen schemafrei verwalten
Tobias Trelle
 
PDF
Morphia, Spring Data & Co
Tobias Trelle
 
PPTX
An introduction to MongoDB and Ruby
Tobias Trelle
 
PPTX
OOP 2013: Praktische Einführung in MongoDB
Tobias Trelle
 
PPTX
MongoDB Munich 2012: Spring Data MongoDB
Tobias Trelle
 
PPTX
MongoDB Live Hacking
Tobias Trelle
 
TDD mit JUnit und Mockito
Tobias Trelle
 
NoSQL - Einführung in Graphen-Datenbanken mit Neo4j
Tobias Trelle
 
Einführung in NoSQL-Datenbanken
Tobias Trelle
 
MongoDB Einführung
Tobias Trelle
 
MongoDB - Riesige Datenmengen schemafrei verwalten
Tobias Trelle
 
Morphia, Spring Data & Co
Tobias Trelle
 
An introduction to MongoDB and Ruby
Tobias Trelle
 
OOP 2013: Praktische Einführung in MongoDB
Tobias Trelle
 
MongoDB Munich 2012: Spring Data MongoDB
Tobias Trelle
 
MongoDB Live Hacking
Tobias Trelle
 

Recently uploaded (20)

PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 

Morphia, Spring Data & Co.

  • 1. codecentric AG 1 Morphia, Spring Data & Co. - Java Persistenz-Frameworks für MongoDB [email protected] @tobiastrelle
  • 2. codecentric AG 2 Tobias Trelle - Senior IT Consultant @ codecentric AG (Düsseldorf) - Organisator MongoDB Usergruppe Düsseldorf - Autor MongoDB-Buch (dpunkt-Verlag)
  • 3. codecentric AG 3 Where have all my tables gone … ORM is dead long live ODM
  • 4. codecentric AG 4 MongoDB?  NoSQL-Datenbank / Open Source  Dokumentenorientiert  Hochperformant, horizontal skalierbar (scale-out)  Replication & Sharding out-of-the-box  Map/Reduce  Geospatial Indexes / Queries
  • 5. codecentric AG 5 Grundkonzept MongoDB-Server Server Database Collection Document Field Tabelle Zeile Spalte Relationales Pendant Aber … Flexibles Schema - Arrays - Rekursiv
  • 6. codecentric AG 6 Document { title: „Praxisbuch Mongo“, version: 0.1, copies_sold: 0, authors: [ { name: „Uwe Seiler“, email: „[email protected]“ }, { name: „Tobias Trelle“, email: „[email protected]“} ] }
  • 7. codecentric AG 7 JSON vs. BSON { hello: "MongoDB" } x18x00x00x00 x02 hellox00 x08x00x00x00MongoDBx00 x00
  • 8. codecentric AG 8 CRUD = IFUR insert(…) find(…), findOne(…) update(…) remove()
  • 9. codecentric AG 9 Java Persistenz mit MongoDB MongoDB Java Driver Spring Data MongoDB Morphia Hibernate OGM Jongo
  • 10. codecentric AG 10 Use Case db.order.find( {"items.quantity": ? } )
  • 11. codecentric AG 11 Mongo Java Driver
  • 12. codecentric AG 12 MongoDB Drivers  One wire protocol for all client languages  A driver implementation per language  Responsibilities:  Converting language dependent data structures   BSON  Generating ObjectId for _id field  Overview: http://www.mongodb.org/display/DOCS/Drivers
  • 13. codecentric AG 13 MongoDB Java Driver One JAR w/o further dependencies: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.11.3</version> </dependency> github: https://github.com/mongodb/mongo-java-driver
  • 14. codecentric AG 14 Java Driver: Connect to MongoDB import com.mongodb.MongoClient; // Default: localhost:27017 mongo = new MongoClient(); // Sharding: mongos server mongo = new MongoClient("mongos01", 4711); // Replica set mongo = new MongoClient(Arrays.asList( new ServerAddress("replicant01", 10001), new ServerAddress("replicant02", 10002), new ServerAddress("replicant03", 10003) ));
  • 15. codecentric AG 15 Java Driver: Database / Collection import com.mongodb.DB; import com.mongodb.DBCollection; DB db = mongo.getDB("test"); DBCollection collection = db.getCollection("foo");
  • 16. codecentric AG 16 Java Driver: Documents import com.mongodb.BasicDBObject; import com.mongodb.DBObject; // insert document DBObject doc = new BasicDBObject(); doc.put("date", new Date()); doc.put("i", 42); collection.insert(doc);
  • 17. codecentric AG 17 Java Driver: Queries import com.mongodb.DBCursor; DBCursor cursor; cursor = collection.find(); // all documents // documents w/ {i: 42} cursor = collection.find( new BasicDBObject("i", 42) ); document = cursor.next(); ...
  • 18. codecentric AG 18 Java Driver: Order Use Case DB db = mongo.getDB("test"); DBCollection collection = db.getCollection("order"); DBObject order; List<DBObject> items = new ArrayList<DBObject>(); DBObject item; // order order = new BasicDBObject(); order.put("date", new Date()); order.put("custInfo" , "Tobias Trelle"); order.put("items", items); // items item = new BasicDBObject(); item.put("quantity", 1); item.put("price", 47.11); item.put("desc", "Item #1"); items.add(item); item = new BasicDBObject(); item.put("quantity", 2); item.put("price", 42.0); item.put("desc", "Item #2"); items.add(item); collection.insert(order);
  • 19. codecentric AG 19 Java Driver: Order Use Case DB db = mongo.getDB("test"); DBCollection collection = db.getCollection("order"); DBObject query; DBObject document; DBCursor cursor; query = new BasicDBObject("items.quantity", 2); cursor = collection.find(query); while ( cursor.hasNext() ) { document = cursor.next(); println(document); }
  • 20. codecentric AG 20 Spring Data MongoDB
  • 21. codecentric AG 21 Spring Data MongoDB – Fact Sheet Vendor VMware / SpringSource License Apache License, Version 2.0 Documentation http://www.springsource.org/spring-data/mongodb Main Features • Repository Support • Object/Document Mapping • Templating
  • 22. codecentric AG 22 Spring Data Common patterns for RDBMS and NoSQL data stores Spring Data RDBMS MongoDB Neo4j … Spring Data JPA CrudRepository PagingAndSortingRepository JpaRepository JPA JDBC Spring Data MongoDB MongoRepository MongoTemplate Spring Data Neo4j Spring Data … GraphRepository Neo4jTemplate Mongo Java Driver Embedded REST Quelle: http://www.infoq.com/articles/spring-data-intro
  • 23. codecentric AG 23 Spring Data MongoDB Templating  Resource abstraction  Configure connections to mongod / mongos node(s)  Collection lifecycle ( create, drop)  Map/Reduce / Aggregation Object Mapping  Annotation based: @Document, @Field, @Index etc.  Classes are mapped to collections, Java Objects to documents Repository Support  Queries are derived from methods signatures  Annotated Queries
  • 24. codecentric AG 24 Spring Data MongoDB: Configuration <!-- Connection to MongoDB server --> <mongo:db-factory host="localhost" port="27017" dbname="test" /> <!-- MongoDB Template --> <bean id="mongoTemplate„ class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> <!-- Package w/ automagic repositories --> <mongo:repositories base-package="mongodb" />
  • 25. codecentric AG 26 Spring Data MongoDB: Object Mapping public class Order { @Id private String id; private Date date; @Field("custInfo") private String customerInfo; List<Item> items; ... } public class Item { private int quantity; private double price; @Field("desc") private String description; ... }
  • 26. codecentric AG 27 Spring Data MongoDB: Repository Support public interface OrderRepository extends MongoRepository<Order, String> { List<Order> findByItemsQuantity(int quantity); @Query("{ "items.quantity": ?0 }") List<Order> findWithQuery(int quantity); }
  • 27. codecentric AG 28 Spring Data MongoDB: Additional Goodies  Map/Reduce / Aggregation framework  Index Management  Support for GridFS  Geopspatial indexes / queries  Optimistic Locking
  • 29. codecentric AG 30 Hibernate OGM MongoDB – Fact Sheet Vendor JBoss / Redhat License GNU LGPL, Version 2.1 Documentation http://www.hibernate.org/subprojects/ogm.html Main Features • JPA API (Subset) • JPQL Query Language
  • 30. codecentric AG 31 Hibernate OGM  Implements JPA API (subset)  JP-QL query are translated to native datastore queries  Supports Infinispan, EhCache, MongoDB
  • 31. codecentric AG 32 Hibernate OGM Architecture Source: http://docs.jboss.org/hibernate/ogm/4.0/reference/en- US/html/ogm-architecture.html#d0e409
  • 32. codecentric AG 33 Hibernate OGM MongoDB: Configuration <persistence version="2.0" …> <persistence-unit name="primary"> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <class>hibernate.Order</class> <class>hibernate.Item</class> <properties> <property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/> <property name="hibernate.ogm.mongodb.database" value=„odm"/> <property name="hibernate.ogm.mongodb.host" value=„localhost"/> <property name="hibernate.ogm.mongodb.port" value=„27017"/> </properties> </persistence-unit> </persistence>
  • 33. codecentric AG 34 Hibernate OGM MongoDB: Object Mapping @Entity @NamedQuery( name="byItemsQuantity", query = "SELECT o FROM Order o JOIN o.items i WHERE i.quantity = :quantity" ) public class Order { @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Id private String id; private Date date; @Column(name = "custInfo") private String customerInfo; @ElementCollection private List<Item> items;
  • 34. codecentric AG 35 Hibernate OGM MongoDB: Object Mapping @Embeddable public class Item { private int quantity; private double price; @Column(name="desc") private String description; ...
  • 35. codecentric AG 36 Hibernate OGM: Summary  Very early beta  Only persist / merge / remove  No query support (yet)  Uses relational API
  • 36. codecentric AG 37 Hibernate OGM: OgmEntityManager
  • 38. codecentric AG 39 Morphia – Fact Sheet Developer Scott Hernandez, James Green License Apache License, Version 2.0 Documentation https://github.com/jmkgreen/morphia/wiki/Overview Main Features • Object/Document Mapping • Custom Query API • DAO support
  • 39. codecentric AG 40 Morphia: Object Mapping public class Order { @Id private ObjectId id; private Date date; @Property("custInfo") private String customerInfo; @Embedded List<Item> items; ... } public class Item { private int quantity; private double price; @Property("desc") private String description; ... }
  • 40. codecentric AG 41 Morphia: Queries public class OrderDao extends BasicDAO<Order, ObjectId> { List<Order> findByItemsQuantity(int quantity) { return find( createQuery().filter("items.quantity", quantity)) .asList(); } List<Order> findByItemsPriceGreaterThan(double price) { return find( createQuery().field("items.price").greaterThan(price) ) .asList(); } … }
  • 41. codecentric AG 42 Morphia: Custom query syntax – why? Morphia Mongo Query = $eq !=, <> $neq >, <, >=,<= $gt, $lt, $gte, $lte in, nin $in, $nin elem $elemMatch … ….
  • 43. codecentric AG 44 Jongo – Fact Sheet Developer Benoît Guérout, Yves Amsellem License Apache License, Version 2.0 Documentation http://jongo.org/ Main Features • Object/Document Mapping • Custom Query API
  • 44. codecentric AG 45 Jongo: Object Mapping public class Order { private ObjectId id; private Date date; @JsonProperty("custInfo") private String customerInfo; List<Item> items; … } public class Item { private int quantity; private double price; @JsonProperty("desc") private String description; … }
  • 45. codecentric AG 46 Jongo: Queries // Java driver API MongoClient mc = new MongoClient(); DB db = mc.getDB("odm_jongo"); // Jongo API entry point Jongo jongo = new Jongo(db); MongoCollection orders = jongo.getCollection("order"); // no DAO needed Iterable<Order> result = orders.find("{"items.quantity": #}", 2).as(Order.class); // supports projection Iterable<X> result = orders.find().fields("{_id:0, date:1, custInfo:1}").as(X.class);
  • 46. codecentric AG 47 Judge yourself … Spring Data MongoDB https://github.com/ttrelle/spring-data-examples Hibernate OGM MongoDB https://github.com/ttrelle/hibernate-ogm-examples Jongo https://github.com/ttrelle/jongo-examples Morphia https://github.com/ttrelle/morphia-mongodb-examples
  • 47. codecentric AG 48 Summary ODM Annotations Queries Java Driver -- Nested BasicDBObject‘s Spring Data MongoDB Custom Interface w/ - derived queries - JSON queries Hibernate OGM JPA JPQL: @Named(Native)Query + EntityManager Jongo Jackson JSON queries via collection wrapper Morphia Custom BasicDAO super class w/ 2 flavours of fluent API
  • 48. codecentric AG 49 Which one should I use? Hibernate OGM Spring Data MongoDB MongoDB Java Driver Morphia JPA JDBC MongoDB Jongo - Ready for production - Supported by 10gen Mature - Ready for production - Active community -Too early to judge - API mismatch The „better“ driver
  • 49. codecentric AG 50 MongoDB User Group Düsseldorf https://www.xing.com/net/mongodb-dus @MongoDUS MUG Düsseldorf
  • 50. codecentric AG 51 QUESTIONS? Tobias Trelle codecentric AG Merscheider Str. 1 42699 Solingen tel +49 (0) 212.233628.47 fax +49 (0) 212.233628.79 mail [email protected] twitter @tobiastrelle www.codecentric.de blog.codecentric.de/en/author/tobias-trelle www.xing.com/net/mongodb-dus