SlideShare une entreprise Scribd logo
1  sur  50
Java Persistenz-Frameworks für MongoDB
Tobias.Trelle@codecentric.de @tobiastrelle
codecentric AG      1
Tobias Trelle


                 - Senior IT Consultant @
                  codecentric AG (Düsseldorf)

                 - Organisator MongoDB
                  Usergruppe Düsseldorf

                 - Autor MongoDB-Buch
                  (dpunkt-Verlag)


codecentric AG        2
Where have all my tables gone …




                 ORM is dead
                 long live   ODM
codecentric AG          3
MongoDB?


      NoSQL-Datenbank / Open Source

      Dokumentenorientiert

      Hochperformant, horizontal skalierbar (scale-out)

      Replication & Sharding out-of-the-box

      Map/Reduce

      Geospatial Indexes / Queries
codecentric AG                  4
Grundkonzept MongoDB-Server


                               Server

Relationales
                              Database
Pendant                                    Aber …
                                           Flexibles
            Tabelle           Collection
                                           Schema

                 Zeile        Document


                                            - Arrays
                 Spalte         Field
                                            - Rekursiv
codecentric AG            5
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        6
JSON vs. BSON


{ hello: "MongoDB" }

x18x00x00x00
   x02
       hellox00
       x08x00x00x00MongoDBx00
x00

codecentric AG   7
CRUD = IFUR


                 insert(…)

                 find(…), findOne(…)

                 update(…)

                 remove()
codecentric AG               8
Java Persistenz mit MongoDB


          MongoDB Java Driver

          Spring Data MongoDB
          Morphia
          Hibernate OGM
          Jongo

codecentric AG        9
Use Case




db.order.find( {"items.quantity": ? } )

codecentric AG   10
Mongo Java Driver


codecentric AG   11
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                               12
MongoDB Java Driver


      One JAR w/o further dependencies:

      <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongo-java-driver</artifactId>
         <version>2.10.0</version>
      </dependency>

      github:
      https://github.com/mongodb/mongo-java-driver



codecentric AG                13
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        14
Java Driver: Database / Collection

import com.mongodb.DB;
import com.mongodb.DBCollection;

DB db = mongo.getDB("test");

DBCollection collection =
   db.getCollection("foo");

codecentric AG          15
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           16
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         17
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                         18
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        19
Spring Data
                  MongoDB

codecentric AG      20
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           21
Spring Data
Common patterns for RDBMS and NoSQL data stores

                                            Spring Data
                                  CrudRepository     PagingAndSortingRepository

                  Spring Data      Spring Data          Spring Data           Spring Data
                      JPA           MongoDB               Neo4j                    …
                 JpaRepository   MongoRepository      GraphRepository
                                 MongoTemplate         Neo4jTemplate


                                                      Embedded     REST


                      JPA        Mongo Java Driver

                     JDBC



                    RDBMS             MongoDB              Neo4j                   …



Quelle: http://www.infoq.com/articles/spring-data-intro
codecentric AG                         22
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                                          23
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             24
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             26
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         27
Spring Data MongoDB: Additional Goodies


        Map/Reduce / Aggregation framework

        Index Management

        Support for GridFS

        Geopspatial indexes / queries

        Optimistic Locking

codecentric AG               28
Hibernate OGM


codecentric AG       29
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           30
Hibernate OGM


         Implements JPA API (subset)

       JP-QL query are translated to native
      datastore queries

         Supports Infinispan, EhCache, MongoDB


codecentric AG          31
Hibernate OGM
Architecture




Source:
http://docs.jboss.org/hibernate/ogm/4.0/reference/en-
     US/html/ogm-architecture.html#d0e409
codecentric AG                                          32
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                                 33
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                              34
Hibernate OGM MongoDB: Object Mapping

@Embeddable
public class Item {


      private int quantity;


      private double price;


      @Column(name="desc") private String description;
      ...




codecentric AG                           35
Hibernate OGM: Summary


         Very early beta

         Only persist / merge / remove

         No query support (yet)

         Uses relational API

codecentric AG             36
Hibernate OGM: OgmEntityManager




codecentric AG      37
Morphia


codecentric AG    38
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           39
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                      40
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                          41
Morphia: Custom query syntax – why?


                 Morphia            Mongo Query
                 =                  $eq
                 !=, <>             $neq
                 >, <, >=,<=        $gt, $lt, $gte, $lte
                 in, nin            $in, $nin
                 elem               $elemMatch
                 …                  ….




codecentric AG                 42
Jongo


codecentric AG   43
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            44
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             45
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             46
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          47
Summary


                      ODM           Queries
                      Annotations
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              48
Which one should I use?

                                                             - Ready for production
                                               Spring Data   - Active community
                                                MongoDB
JPA              Hibernate OGM
                         -Too early to judge                                      Dead
                         - API mismatch                            Morphia
                                                                                         The „better“ driver
                                                                                         Jongo


JDBC                                            MongoDB Java Driver
                                                                               - Ready for production
                                                                               - Supported by 10gen



                                                       MongoDB


codecentric AG                             49
MUG Düsseldorf

MongoDB User Group Düsseldorf

https://www.xing.com/net/mongodb-dus

@MongoDUS




codecentric AG   50
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

codecentric AG                              51

Contenu connexe

Tendances

MongoDB Live Hacking
MongoDB Live HackingMongoDB Live Hacking
MongoDB Live HackingTobias Trelle
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDBJeff Yemin
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo dbVladimir Ilic
 
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
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 
FIWARE Global Summit - Hands-On NGSI-LD
FIWARE Global Summit - Hands-On NGSI-LDFIWARE Global Summit - Hands-On NGSI-LD
FIWARE Global Summit - Hands-On NGSI-LDFIWARE
 
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
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...MongoDB
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP formatForest Mars
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkitpetertmarks
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaMongoDB
 
mongoDB Performance
mongoDB PerformancemongoDB Performance
mongoDB PerformanceMoshe Kaplan
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud FoundryJoshua Long
 
introtomongodb
introtomongodbintrotomongodb
introtomongodbsaikiran
 
Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters MongoDB
 

Tendances (19)

MongoDB Live Hacking
MongoDB Live HackingMongoDB Live Hacking
MongoDB Live Hacking
 
Morphia: Simplifying Persistence for Java and MongoDB
Morphia:  Simplifying Persistence for Java and MongoDBMorphia:  Simplifying Persistence for Java and MongoDB
Morphia: Simplifying Persistence for Java and MongoDB
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo db
 
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
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
FIWARE Global Summit - Hands-On NGSI-LD
FIWARE Global Summit - Hands-On NGSI-LDFIWARE Global Summit - Hands-On NGSI-LD
FIWARE Global Summit - Hands-On NGSI-LD
 
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
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
 
mongoDB Performance
mongoDB PerformancemongoDB Performance
mongoDB Performance
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundry
 
introtomongodb
introtomongodbintrotomongodb
introtomongodb
 
Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters
 

En vedette

Deepak ib solved paper
Deepak ib solved paperDeepak ib solved paper
Deepak ib solved paperDeepak R Gorad
 
Theanatomyofanentrepreneur 100105180411-phpapp01
Theanatomyofanentrepreneur 100105180411-phpapp01Theanatomyofanentrepreneur 100105180411-phpapp01
Theanatomyofanentrepreneur 100105180411-phpapp01Deepak R Gorad
 
Being A Socially Responsible Social Developer: Mobile App Security
Being A Socially Responsible Social Developer: Mobile App SecurityBeing A Socially Responsible Social Developer: Mobile App Security
Being A Socially Responsible Social Developer: Mobile App SecurityDoug Sillars
 
Somnium Network журнал
Somnium Network журналSomnium Network журнал
Somnium Network журналonlinesarabotok
 
Mobile Web Performance using WebPageTest and HTTPArchive
Mobile Web Performance using WebPageTest and HTTPArchiveMobile Web Performance using WebPageTest and HTTPArchive
Mobile Web Performance using WebPageTest and HTTPArchiveDoug Sillars
 
deepak gorad Final csr
deepak gorad Final csrdeepak gorad Final csr
deepak gorad Final csrDeepak R Gorad
 
Promotion guide
Promotion guidePromotion guide
Promotion guideseitwenwei
 
Power electronics projects
Power electronics projectsPower electronics projects
Power electronics projectsSenthil Kumar
 
World continents and oceans
World continents and oceansWorld continents and oceans
World continents and oceansjawed shaikh
 
Scada for power system automation - Power Systems final year Project
Scada for power system automation - Power Systems final year ProjectScada for power system automation - Power Systems final year Project
Scada for power system automation - Power Systems final year ProjectSenthil Kumar
 
Xamarin Mobile March 2014
Xamarin Mobile March 2014Xamarin Mobile March 2014
Xamarin Mobile March 2014Joe Koletar
 
A Literate Environment Project
A Literate Environment ProjectA Literate Environment Project
A Literate Environment Projectslutke
 
Enhance WordPress Search Using Sphinx
Enhance WordPress Search Using SphinxEnhance WordPress Search Using Sphinx
Enhance WordPress Search Using SphinxRoshan Bhattarai
 

En vedette (20)

Deepak ib solved paper
Deepak ib solved paperDeepak ib solved paper
Deepak ib solved paper
 
Electricmotors6
Electricmotors6Electricmotors6
Electricmotors6
 
Theanatomyofanentrepreneur 100105180411-phpapp01
Theanatomyofanentrepreneur 100105180411-phpapp01Theanatomyofanentrepreneur 100105180411-phpapp01
Theanatomyofanentrepreneur 100105180411-phpapp01
 
Electronicdevices
ElectronicdevicesElectronicdevices
Electronicdevices
 
Being A Socially Responsible Social Developer: Mobile App Security
Being A Socially Responsible Social Developer: Mobile App SecurityBeing A Socially Responsible Social Developer: Mobile App Security
Being A Socially Responsible Social Developer: Mobile App Security
 
Somnium Network журнал
Somnium Network журналSomnium Network журнал
Somnium Network журнал
 
Mobile Web Performance using WebPageTest and HTTPArchive
Mobile Web Performance using WebPageTest and HTTPArchiveMobile Web Performance using WebPageTest and HTTPArchive
Mobile Web Performance using WebPageTest and HTTPArchive
 
deepak gorad Final csr
deepak gorad Final csrdeepak gorad Final csr
deepak gorad Final csr
 
Promotion guide
Promotion guidePromotion guide
Promotion guide
 
Power electronics projects
Power electronics projectsPower electronics projects
Power electronics projects
 
World continents and oceans
World continents and oceansWorld continents and oceans
World continents and oceans
 
Scada for power system automation - Power Systems final year Project
Scada for power system automation - Power Systems final year ProjectScada for power system automation - Power Systems final year Project
Scada for power system automation - Power Systems final year Project
 
Xamarin Mobile March 2014
Xamarin Mobile March 2014Xamarin Mobile March 2014
Xamarin Mobile March 2014
 
A Literate Environment Project
A Literate Environment ProjectA Literate Environment Project
A Literate Environment Project
 
Drgorad
DrgoradDrgorad
Drgorad
 
Enhance WordPress Search Using Sphinx
Enhance WordPress Search Using SphinxEnhance WordPress Search Using Sphinx
Enhance WordPress Search Using Sphinx
 
Vlsi projects
Vlsi projectsVlsi projects
Vlsi projects
 
Abstract2
Abstract2Abstract2
Abstract2
 
Mec chapter 8
Mec chapter 8Mec chapter 8
Mec chapter 8
 
Tqm deepak R Gorad
Tqm deepak R  GoradTqm deepak R  Gorad
Tqm deepak R Gorad
 

Similaire à BedCon 2013 - Java Persistenz-Frameworks für MongoDB

Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Kuo-Chun Su
 
Mongo db halloween party
Mongo db halloween partyMongo db halloween party
Mongo db halloween partyAndrea Balducci
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHPichikaway
 
Mdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_searchMdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_searchDaniel M. Farrell
 
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...Pôle Systematic Paris-Region
 
Monogo db in-action
Monogo db in-actionMonogo db in-action
Monogo db in-actionChi Lee
 
Node Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialPHP Support
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongoMichael Bright
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and PythonMike Bright
 
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB
 

Similaire à BedCon 2013 - Java Persistenz-Frameworks für MongoDB (20)

Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹
 
mongodb tutorial
mongodb tutorialmongodb tutorial
mongodb tutorial
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db halloween party
Mongo db halloween partyMongo db halloween party
Mongo db halloween party
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
 
Mdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_searchMdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_search
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...
Open-Source Analytics Stack on MongoDB, with Schema, Pierre-Alain Jachiet and...
 
Monogo db in-action
Monogo db in-actionMonogo db in-action
Monogo db in-action
 
Node Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js TutorialNode Js, AngularJs and Express Js Tutorial
Node Js, AngularJs and Express Js Tutorial
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and Python
 
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
MongoDB
MongoDBMongoDB
MongoDB
 

Plus de Tobias Trelle

TDD mit JUnit und Mockito
TDD mit JUnit und MockitoTDD mit JUnit und Mockito
TDD mit JUnit und MockitoTobias Trelle
 
NoSQL - Einführung in Graphen-Datenbanken mit Neo4j
NoSQL - Einführung in Graphen-Datenbanken mit Neo4jNoSQL - Einführung in Graphen-Datenbanken mit Neo4j
NoSQL - Einführung in Graphen-Datenbanken mit Neo4jTobias Trelle
 
Einführung in NoSQL-Datenbanken
Einführung in NoSQL-DatenbankenEinführung in NoSQL-Datenbanken
Einführung in NoSQL-DatenbankenTobias Trelle
 
MongoDB - Riesige Datenmengen schemafrei verwalten
MongoDB - Riesige Datenmengen schemafrei verwaltenMongoDB - Riesige Datenmengen schemafrei verwalten
MongoDB - Riesige Datenmengen schemafrei verwaltenTobias Trelle
 
Test Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTest Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTobias Trelle
 
Morphia, Spring Data & Co
Morphia, Spring Data & CoMorphia, Spring Data & Co
Morphia, Spring Data & CoTobias Trelle
 
An introduction to MongoDB and Ruby
An introduction to MongoDB and RubyAn introduction to MongoDB and Ruby
An introduction to MongoDB and RubyTobias Trelle
 
OOP 2013: Praktische Einführung in MongoDB
OOP 2013: Praktische Einführung in MongoDBOOP 2013: Praktische Einführung in MongoDB
OOP 2013: Praktische Einführung in MongoDBTobias Trelle
 
MongoDB Munich 2012: Spring Data MongoDB
MongoDB Munich 2012: Spring Data MongoDBMongoDB Munich 2012: Spring Data MongoDB
MongoDB Munich 2012: Spring Data MongoDBTobias Trelle
 

Plus de Tobias Trelle (10)

TDD mit JUnit und Mockito
TDD mit JUnit und MockitoTDD mit JUnit und Mockito
TDD mit JUnit und Mockito
 
NoSQL - Einführung in Graphen-Datenbanken mit Neo4j
NoSQL - Einführung in Graphen-Datenbanken mit Neo4jNoSQL - Einführung in Graphen-Datenbanken mit Neo4j
NoSQL - Einführung in Graphen-Datenbanken mit Neo4j
 
Einführung in NoSQL-Datenbanken
Einführung in NoSQL-DatenbankenEinführung in NoSQL-Datenbanken
Einführung in NoSQL-Datenbanken
 
MongoDB Einführung
MongoDB EinführungMongoDB Einführung
MongoDB Einführung
 
MongoDB - Riesige Datenmengen schemafrei verwalten
MongoDB - Riesige Datenmengen schemafrei verwaltenMongoDB - Riesige Datenmengen schemafrei verwalten
MongoDB - Riesige Datenmengen schemafrei verwalten
 
Test Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTest Automation for NoSQL Databases
Test Automation for NoSQL Databases
 
Morphia, Spring Data & Co
Morphia, Spring Data & CoMorphia, Spring Data & Co
Morphia, Spring Data & Co
 
An introduction to MongoDB and Ruby
An introduction to MongoDB and RubyAn introduction to MongoDB and Ruby
An introduction to MongoDB and Ruby
 
OOP 2013: Praktische Einführung in MongoDB
OOP 2013: Praktische Einführung in MongoDBOOP 2013: Praktische Einführung in MongoDB
OOP 2013: Praktische Einführung in MongoDB
 
MongoDB Munich 2012: Spring Data MongoDB
MongoDB Munich 2012: Spring Data MongoDBMongoDB Munich 2012: Spring Data MongoDB
MongoDB Munich 2012: Spring Data MongoDB
 

BedCon 2013 - Java Persistenz-Frameworks für MongoDB

  • 1. Java Persistenz-Frameworks für MongoDB Tobias.Trelle@codecentric.de @tobiastrelle codecentric AG 1
  • 2. Tobias Trelle - Senior IT Consultant @ codecentric AG (Düsseldorf) - Organisator MongoDB Usergruppe Düsseldorf - Autor MongoDB-Buch (dpunkt-Verlag) codecentric AG 2
  • 3. Where have all my tables gone … ORM is dead long live ODM codecentric AG 3
  • 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 4
  • 5. Grundkonzept MongoDB-Server Server Relationales Database Pendant Aber … Flexibles Tabelle Collection Schema Zeile Document - Arrays Spalte Field - Rekursiv codecentric AG 5
  • 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 6
  • 7. JSON vs. BSON { hello: "MongoDB" } x18x00x00x00 x02 hellox00 x08x00x00x00MongoDBx00 x00 codecentric AG 7
  • 8. CRUD = IFUR insert(…) find(…), findOne(…) update(…) remove() codecentric AG 8
  • 9. Java Persistenz mit MongoDB MongoDB Java Driver Spring Data MongoDB Morphia Hibernate OGM Jongo codecentric AG 9
  • 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 12
  • 13. MongoDB Java Driver One JAR w/o further dependencies: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.10.0</version> </dependency> github: https://github.com/mongodb/mongo-java-driver codecentric AG 13
  • 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 14
  • 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 15
  • 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 16
  • 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 17
  • 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 18
  • 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 19
  • 20. Spring Data MongoDB codecentric AG 20
  • 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 21
  • 22. Spring Data Common patterns for RDBMS and NoSQL data stores Spring Data CrudRepository PagingAndSortingRepository Spring Data Spring Data Spring Data Spring Data JPA MongoDB Neo4j … JpaRepository MongoRepository GraphRepository MongoTemplate Neo4jTemplate Embedded REST JPA Mongo Java Driver JDBC RDBMS MongoDB Neo4j … Quelle: http://www.infoq.com/articles/spring-data-intro codecentric AG 22
  • 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 23
  • 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 24
  • 25. 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 26
  • 26. 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 27
  • 27. Spring Data MongoDB: Additional Goodies Map/Reduce / Aggregation framework Index Management Support for GridFS Geopspatial indexes / queries Optimistic Locking codecentric AG 28
  • 29. 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 30
  • 30. Hibernate OGM Implements JPA API (subset) JP-QL query are translated to native datastore queries Supports Infinispan, EhCache, MongoDB codecentric AG 31
  • 32. 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 33
  • 33. 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 34
  • 34. Hibernate OGM MongoDB: Object Mapping @Embeddable public class Item { private int quantity; private double price; @Column(name="desc") private String description; ... codecentric AG 35
  • 35. Hibernate OGM: Summary Very early beta Only persist / merge / remove No query support (yet) Uses relational API codecentric AG 36
  • 38. 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 39
  • 39. 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 40
  • 40. 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 41
  • 41. Morphia: Custom query syntax – why? Morphia Mongo Query = $eq !=, <> $neq >, <, >=,<= $gt, $lt, $gte, $lte in, nin $in, $nin elem $elemMatch … …. codecentric AG 42
  • 43. 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 44
  • 44. 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 45
  • 45. 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 46
  • 46. 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 47
  • 47. Summary ODM Queries Annotations 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 48
  • 48. Which one should I use? - Ready for production Spring Data - Active community MongoDB JPA Hibernate OGM -Too early to judge Dead - API mismatch Morphia The „better“ driver Jongo JDBC MongoDB Java Driver - Ready for production - Supported by 10gen MongoDB codecentric AG 49
  • 49. MUG Düsseldorf MongoDB User Group Düsseldorf https://www.xing.com/net/mongodb-dus @MongoDUS codecentric AG 50
  • 50. 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 codecentric AG 51