javadevelopmentwithmongodb1-100430175419-phpapp02

Upload: freddy-chilon-vargas

Post on 04-Apr-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    1/25

    Java Development withMongoDBJames Williams

    Software Engineer, BT/Ribbit

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    2/25

    Agenda

    Java Driver basicsMaking ConnectionsManaging CollectionsBasicDBObjectBuilder

    Document QueriesGridFS

    MorphiaBeyond the Java language

    Groovy utilitiesGrails plugin

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    3/25

    Making a Connection

    import com.mongodb.Mongo;

    import com.mongodb.DB;

    Mongo m = new Mongo();

    Mongo m = new Mongo( "localhost" );Mongo m = new Mongo( "localhost" , 27017 );

    DB db = m.getDB( "mydb" );

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    4/25

    Working with Collections

    Getting all collections in the databaseSet colls = db.getCollectionNames();

    for (String s : colls) {

    System.out.println(s);

    }Getting a single collection

    DBCollection coll = db.getCollection("testCollection")

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    5/25

    Inserting Documents

    BasicDBObject doc = new BasicDBObject();

    doc.put("name", "MongoDB");

    doc.put("type", "database");

    doc.put("count", 1);

    BasicDBObject info = new BasicDBObject();

    info.put("x", 203);

    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    6/25

    BasicDBObjectBuilder

    Utility for building objectsCan coerce Maps (and possibly JSON*) to DBObjectsExample:

    BasicDBObjectBuilder.start()

    .add( "name" , "eliot" )

    .add( "number" , 17 )

    .get();

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    7/25

    Document Queries

    DBObject myDoc = coll.findOne();

    // can also use

    BasicDBObject query = new BasicDBObject(); query.put("i", 71);

    DBCursor cur = coll.find(query);

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    8/25

    GridFS

    mechanism for storing files larger than 4MBfiles are chunked allowing fetching of a portion or out oforderchunking is mostly transparent to underlying operating

    systemcan store files in buckets, a MongoDB metaphor for foldersdefault is the fs bucket

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    9/25

    Saving a file to GridFS

    def mongo = new Mongo(host)

    def gridfs = new GridFS(mongo.getDB("db"))

    def save(inputStream, contentType, filename) {def inputFile = gridfs.createFile(inputStream)inputFile.setContentType(contentType)inputFile.setFilename(filename)inputFile.save()

    }

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    10/25

    Retrieving/Deleting a file

    def retrieveFile(String filename) {

    return gridfs.findOne(filename)

    }

    def deleteFile(String filename) {

    gridfs.remove(filename)

    }

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    11/25

    Morphia

    Apache 2 Licensedbrings Hibernate/JPA paradigms to MongoDBallows annotating of POJOs to make converting thembetween MongoDB and Java very easy

    supports DAO abstractionsoffers type-safe query supportcompatible with GWT, Guice, Spring, and DI frameworks

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    12/25

    Morphia Annotations

    @Id@Entity@Embedded@Reference

    @Indexed@Serialized@Property

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    13/25

    Creating a Morphia POJO

    import com.google.code.morphia.annotations.*;

    @Entity("collectionName")

    public class Contact {

    @Id

    private String id; //generated by MongoDB

    private String firstName;

    private String lastName;

    @Embedded

    private List phoneNumbers;

    // getters and setters

    }

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    14/25

    Mapping a POJO to a Mongo doc

    Morphia morphia = ...;

    Mongo mongo = ...;

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

    Contact contact = ...;

    // map the contact to a DBObject

    DBObject contactObj = morphia.toDBObject(contact);

    db.getCollection("personal").save(contactObj);

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    15/25

    Getting a POJO from a Mongo doc

    Morphia morphia = ...;

    Mongo mongo = ...;

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

    String contactId = ...;

    //load the object from the collection

    BasicDBObject idObj = new BasicDBObject(

    "_id", new ObjectId(contactId)

    );

    BasicDBObject obj = (BasicDBObject)

    db.getCollection("personal").findOne(idObj);

    Contact contact = morphia.fromDBObject(Contact.class, obj);

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    16/25

    DAOs

    Encapsulate saving and retrieving objectsAuto-converts to and from POJOsCan provide constraints on searchesKey functions:

    get()find() or find(constraints)findOne(constraints)deleteById()

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    17/25

    DAO Example

    import com.mongodb.Mongo

    import com.google.code.morphia.*

    class EntryDAO extends DAO {

    public EntryDAO(Morphia morphia, Mongo mongo) {

    super(mongo, morphia, "entries")

    }

    }

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    18/25

    Constraints Examples

    dao.find(new Constraints() .

    orderByDesc("dateCreated")

    ).asList()

    dao.find(new Constraints()

    .field("dateCreated").greaterThanOrEqualTo(date).field("title").

    equalTo(params.title)

    ).asList()

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    19/25

    Beyond the Java Language

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    20/25

    MongoDB with Groovy

    Metaprogramming with MongoDB can reduce LOCDynamic findersFluent interface mirroring Ruby and Python

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    21/25

    Groovy + MongoDB

    JavaBasicDBObject doc = new BasicDBObject();

    doc.put("name", "MongoDB");

    doc.put("type", "database");

    doc.put("count", 1);

    coll.insert(doc);

    Groovierdef doc = [name:"MongoDB",type:"database", count:1, info:

    [x:203, y:102] ] as BasicDBObject

    coll.insert(doc)

    Grooviest (using groovy-mongo)coll.insert([name:"MongoDB", type:"database", info: [x:203, y:102]])

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    22/25

    Dynamic Finders

    can build complex queries at runtimecan even reach into objects for addition query parameters

    Ex. collection.findByAuthorAndPostCreatedGreaterThan(...)

    collection.findByComments_CreatedOn(...)

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    23/25

    How dynamic finders work

    Groovy receives the request for the methodThe method is not found (invoking methodMissing)The method name used to construct a query templateThe method is cached

    The method is invoked with the parametersFuture invocations use the cached method

  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    24/25

    MongoDB Grails Plugin

    Replaces JDBC layer in Grails applicationsCan use dynamic findersRequires only slight modifications to domain classeshttp://github.com/mpriatel/mongodb-grails

    http://github.com/mpriatel/mongodb-grails
  • 7/29/2019 javadevelopmentwithmongodb1-100430175419-phpapp02

    25/25

    Links

    Personal Blog: http://jameswilliams.be/blogTwitter: http://twitter.com/ecspike

    Morphia: http://code.google.com/p/morphia

    Utilities for Groovy: http://github.com/jwill/groovy-mongoMongoDB Grails plugin: http://github.com/mpriatel/mongodb-grails

    http://github.com/mpriatel/mongodb-grailshttp://github.com/mpriatel/mongodb-grailshttp://github.com/mpriatel/mongodb-grailshttp://github.com/jwill/groovy-mongohttp://github.com/jwill/groovy-mongohttp://code.google.com/p/morphiahttp://github.com/mpriatel/mongodb-grailshttp://github.com/mpriatel/mongodb-grailshttp://github.com/jwill/groovy-mongohttp://code.google.com/p/morphiahttp://twitter.com/ecspikehttp://jameswilliams.be/blog