Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Morphia, Spring Data & Co.

8.094 Aufrufe

Veröffentlicht am

After a short introduction to the Java driver for MongoDB, we'll have a look at the more abtract persistence frameworks like Morphia, Spring Data, Jongo and Hibernate OGM.

Veröffentlicht in: Technologie, Bildung
  • Als Erste(r) kommentieren

Morphia, Spring Data & Co.

  1. 1. codecentric AG 1 Morphia, Spring Data & Co. - Java Persistenz-Frameworks für MongoDB Tobias.Trelle@codecentric.de @tobiastrelle
  2. 2. codecentric AG 2 Tobias Trelle - Senior IT Consultant @ codecentric AG (Düsseldorf) - Organisator MongoDB Usergruppe Düsseldorf - Autor MongoDB-Buch (dpunkt-Verlag)
  3. 3. codecentric AG 3 Where have all my tables gone … ORM is dead long live ODM
  4. 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. 5. codecentric AG 5 Grundkonzept MongoDB-Server Server Database Collection Document Field Tabelle Zeile Spalte Relationales Pendant Aber … Flexibles Schema - Arrays - Rekursiv
  6. 6. 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“} ] }
  7. 7. codecentric AG 7 JSON vs. BSON { hello: "MongoDB" } x18x00x00x00 x02 hellox00 x08x00x00x00MongoDBx00 x00
  8. 8. codecentric AG 8 CRUD = IFUR insert(…) find(…), findOne(…) update(…) remove()
  9. 9. codecentric AG 9 Java Persistenz mit MongoDB MongoDB Java Driver Spring Data MongoDB Morphia Hibernate OGM Jongo
  10. 10. codecentric AG 10 Use Case db.order.find( {"items.quantity": ? } )
  11. 11. codecentric AG 11 Mongo Java Driver
  12. 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. 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. 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. 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. 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. 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. 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. 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. 20. codecentric AG 20 Spring Data MongoDB
  21. 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. 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. 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. 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. 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. 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. 27. codecentric AG 28 Spring Data MongoDB: Additional Goodies  Map/Reduce / Aggregation framework  Index Management  Support for GridFS  Geopspatial indexes / queries  Optimistic Locking
  28. 28. codecentric AG 29 Hibernate OGM
  29. 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. 30. codecentric AG 31 Hibernate OGM  Implements JPA API (subset)  JP-QL query are translated to native datastore queries  Supports Infinispan, EhCache, MongoDB
  31. 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. 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. 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. 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. 35. codecentric AG 36 Hibernate OGM: Summary  Very early beta  Only persist / merge / remove  No query support (yet)  Uses relational API
  36. 36. codecentric AG 37 Hibernate OGM: OgmEntityManager
  37. 37. codecentric AG 38 Morphia
  38. 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. 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. 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. 41. codecentric AG 42 Morphia: Custom query syntax – why? Morphia Mongo Query = $eq !=, <> $neq >, <, >=,<= $gt, $lt, $gte, $lte in, nin $in, $nin elem $elemMatch … ….
  42. 42. codecentric AG 43 Jongo
  43. 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. 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. 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. 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. 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. 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. 49. codecentric AG 50 MongoDB User Group Düsseldorf https://www.xing.com/net/mongodb-dus @MongoDUS MUG Düsseldorf
  50. 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 Tobias.Trelle@codecentric.de twitter @tobiastrelle www.codecentric.de blog.codecentric.de/en/author/tobias-trelle www.xing.com/net/mongodb-dus

×