java development with mongodb
Post on 18-Oct-2014
52.547 views
DESCRIPTION
Presented at MongoSF on April 30, 2010.TRANSCRIPT
![Page 1: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/1.jpg)
Java Development with MongoDBJames Williams
Software Engineer, BT/Ribbit
![Page 2: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/2.jpg)
Agenda
Java Driver basicsMaking ConnectionsManaging CollectionsBasicDBObjectBuilderDocument QueriesGridFS
MorphiaBeyond the Java language
Groovy utilitiesGrails plugin
![Page 3: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/3.jpg)
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" );
![Page 4: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/4.jpg)
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")
![Page 5: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/5.jpg)
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);
![Page 6: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/6.jpg)
BasicDBObjectBuilder
Utility for building objectsCan coerce Maps (and possibly JSON*) to DBObjects Example:
BasicDBObjectBuilder.start() .add( "name" , "eliot" ) .add( "number" , 17 ) .get();
![Page 7: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/7.jpg)
Document Queries
DBObject myDoc = coll.findOne();// can also use BasicDBObject query = new BasicDBObject(); query.put("i", 71); DBCursor cur = coll.find(query);
![Page 8: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/8.jpg)
GridFS
mechanism for storing files larger than 4MBfiles are chunked allowing fetching of a portion or out of orderchunking is mostly transparent to underlying operating systemcan store files in buckets, a MongoDB metaphor for foldersdefault is the fs bucket
![Page 9: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/9.jpg)
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()}
![Page 10: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/10.jpg)
Retrieving/Deleting a file
def retrieveFile(String filename) { return gridfs.findOne(filename)}
def deleteFile(String filename) { gridfs.remove(filename)}
![Page 11: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/11.jpg)
Morphia
Apache 2 Licensedbrings Hibernate/JPA paradigms to MongoDBallows annotating of POJOs to make converting them between MongoDB and Java very easysupports DAO abstractionsoffers type-safe query supportcompatible with GWT, Guice, Spring, and DI frameworks
![Page 12: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/12.jpg)
Morphia Annotations
@Id@Entity@Embedded@Reference@Indexed@Serialized@Property
![Page 13: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/13.jpg)
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<PhoneNumber> phoneNumbers;
// getters and setters}
![Page 14: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/14.jpg)
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);
![Page 15: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/15.jpg)
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);
![Page 16: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/16.jpg)
DAOs
Encapsulate saving and retrieving objectsAuto-converts to and from POJOsCan provide constraints on searchesKey functions:
get(<mongoId>)find() or find(constraints)findOne(constraints)deleteById(<mongoId>)
![Page 17: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/17.jpg)
DAO Example
import com.mongodb.Mongoimport com.google.code.morphia.*
class EntryDAO extends DAO<BlogEntry,String> { public EntryDAO(Morphia morphia, Mongo mongo) {super(mongo, morphia, "entries") }}
![Page 18: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/18.jpg)
Constraints Examples
dao.find(new Constraints() .orderByDesc("dateCreated")).asList()
dao.find(new Constraints().field("dateCreated").greaterThanOrEqualTo(date).field("title").equalTo(params.title)).asList()
![Page 19: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/19.jpg)
Beyond the Java Language
![Page 20: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/20.jpg)
MongoDB with Groovy
Metaprogramming with MongoDB can reduce LOCDynamic findersFluent interface mirroring Ruby and Python
![Page 21: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/21.jpg)
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]])
![Page 22: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/22.jpg)
Dynamic Finders
can build complex queries at runtimecan even reach into objects for addition query parameters
Ex. collection.findByAuthorAndPostCreatedGreaterThan(...) collection.findByComments_CreatedOn(...)
![Page 23: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/23.jpg)
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 cachedThe method is invoked with the parametersFuture invocations use the cached method
![Page 24: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/24.jpg)
MongoDB Grails Plugin
Replaces JDBC layer in Grails applicationsCan use dynamic findersRequires only slight modifications to domain classeshttp://github.com/mpriatel/mongodb-grails
![Page 25: Java development with MongoDB](https://reader034.vdocuments.net/reader034/viewer/2022051311/544319dab1af9f2d0a8b47d6/html5/thumbnails/25.jpg)
Links
Personal Blog: http://jameswilliams.be/blogTwitter: http://twitter.com/ecspike
Morphia: http://code.google.com/p/morphiaUtilities for Groovy: http://github.com/jwill/groovy-mongoMongoDB Grails plugin: http://github.com/mpriatel/mongodb-grails