java development with mongodb (james williams)

Post on 18-Oct-2014

8.655 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

Java Development with MongoDBJames Williams

Software Engineer, BT/Ribbit

Agenda

• Java Driver basicso Making Connectionso Managing Collectionso BasicDBObjectBuildero Document Querieso GridFS

• Morphia• Beyond the Java language

o Groovy utilitieso Grails plugin

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" );

Working with Collections

• Getting all collections in the databaseSet<String> colls = db.getCollectionNames(); for (String s : colls) {   System.out.println(s); }• Getting a single collectionDBCollection coll = db.getCollection("testCollection")

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);

BasicDBObjectBuilder

• Utility for building objects• Can coerce Maps (and possibly JSON*) to DBObjects•  Example:BasicDBObjectBuilder.start()    .add( "name" , "eliot" )    .add( "number" , 17 )    .get();

Document Queries

DBObject myDoc = coll.findOne();// can also use BasicDBObjectBuilderBasicDBObject query = new BasicDBObject(); query.put("i", 71); Cursor cur = coll.find(query);

GridFS

• mechanism for storing files larger than 4MB• files are chunked allowing fetching of a portion or out of

order• chunking is mostly transparent to underlying operating

system• can store files in buckets, a MongoDB metaphor for folders• default is the fs bucket

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()}

Retrieving/Deleting a file

def retrieveFile(String filename) {    return gridfs.findOne(filename)}

def deleteFile(String filename) {    gridfs.remove(filename)}

Morphia

• Apache 2 Licensed• brings Hibernate/JPA paradigms to MongoDB• allows annotating of POJOs to make converting them

between MongoDB and Java very easy• supports DAO abstractions• offers type-safe query support• compatible with GWT, Guice, Spring, and DI frameworks

Creating a Morphia POJO

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

@Entity("collectionName")public class Contact {    @Id    private String id;    //generated by MongoDB

    private String firstName;    private String lastName;    @Embedded    private List<PhoneNumber> phoneNumbers;

    // getters and setters}

Mapping a POJO to a Mongo doc

Morphia morphia = ...;Mongo mongo = ...;DB db = mongo.getDB("contacts");

Contact contact = ...;

// map the contact to a DBObjectDBObject contactObj = morphia.toDBObject(contact);

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

Getting a POJO from a Mongo doc

Morphia morphia = ...;Mongo mongo = ...;DB db = mongo.getDB("contacts");

String contactId = ...;

//load the object from the collectionBasicDBObject idObj = new BasicDBObject(    "_id", new ObjectId(contactId));BasicDBObject obj = (BasicDBObject)  db.getCollection("personal").findOne(idObj);Contact contact = morphia.fromDBObject(Contact.class, obj);

Beyond the Java Language

MongoDB with Groovy

• Metaprogramming with MongoDB can reduce LOC• Dynamic finders• Fluent interface mirroring Ruby and Python

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 BasicDBObjectcoll.insert(doc)

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

y:102]])

Dynamic Finders

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

Ex. collection.findByAuthorAndPostCreatedGreaterThan(...)    collection.findByComments_CreatedOn(...) 

How dynamic finders work

• Groovy receives the request for the method• The method is not found (invoking methodMissing)• The method name used to construct a query template• The method is cached• The method is invoked with the parameters• Future invocations use the cached method

MongoDB Grails Plugin

• Replaces JDBC layer in Grails applications• Can use dynamic finders• Requires only slight modifications to domain classes• http://github.com/mpriatel/mongodb-grails

Links

• Personal Blog: http://jameswilliams.be/blog• Twitter: http://twitter.com/ecspike

• Morphia: http://code.google.com/p/morphia• Utilities for Groovy: http://github.com/jwill/groovy-mongo• MongoDB Grails plugin:

 http://github.com/mpriatel/mongodb-grails

top related