Accueil > Dojo, Mongo JEE, MongoDB > Mongo JEE [step1]

Mongo JEE [step1]


In [step0] we have introduced Mongo JEE articles, install and initialize Mongo DB websites database with Mongo Shell scripts. In this article we will do the same thing with Java code by using :

Download

You can download step1.zip which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this :

  • scripts folder contains the Javascript mongo operation (insert, remove etc) with Mongo Shell explained in the [step0].
  • the Java package org.samples.mongodb.operations.javadriver contains the same Java mongo operations with Java Mongo Driver.
  • the Java package org.samples.mongodb.operations.pojomapper.mongojack contains the same Java mongo operations with Pojo Mapper MongoJack.

Download JARs with maven

Each step*. project that I will provide use JARs. I could download at hand the JARs (awfull work), but I prefer using maven to manage dependencies.

So each step* project contains a pom.xml.

But as maven is not used by the whole people, the step* project contains the lib folder which hosts JARs and classpath of the eclipse project uses those JARs.

If you wish to download the JARs, you can do it with the command :

mvn process-resources

This command download the JARs from the central maven repository, and copy them in the lib folder.

Mongo Operations

Mongo Java Driver

In this section we use the Mongo Java Driver. I suggest you to read the Getting Started with Java Driver article which list the basic features of the driver.

Download driver

The driver is managed with the lib/mongo-java-driver-2.11.1.jar. To download it, I have used this maven dependency :

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

Here the full pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.samples.mongodb</groupId>
	<artifactId>step1</artifactId>
	<packaging>pom</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.1</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>process-resources</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>lib</outputDirectory>
							<overWriteReleases>true</overWriteReleases>
							<overWriteSnapshots>true</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
							<excludeTypes>libd</excludeTypes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>

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

</project>

InsertLogsWithMongoJavaDriver.java

In the [step0], we have inserted logs with the following Javascript Mongo Shell :

for ( var i = 0; i < 100; i++) {
    db.logs.insert({
        "url" : "http://www.mongodb.org/",
        "created" : new Date()
    })
}

Here the same code with Java Mongo Driver :

package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;
import java.util.Calendar;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class InsertLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// Insert logs with DB object
			DBObject log = null;
			for (int i = 0; i < 100; i++) {
				log = new BasicDBObject();
				log.put("url", "https://github.com/angelozerr/mongo-jee");
				log.put("created", Calendar.getInstance().getTime());
				coll.insert(log);
			}

		} finally {
			mongo.close();
		}

	}
}

An interesting test to do, is to start this Java main without starting the Mongo DB. The following exception is thrown :

ATTENTION: Exception executing isMaster command on localhost/127.0.0.1:27017
java.net.ConnectException: Connection refused: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)

by the line code :

coll.insert(log);

So getting connection and getting DB collection code doesn’t throw exception even if DB is not started.

FindLogsWithMongoJavaDriver.java

In the [step0], we have displayed the total logs with the following Javascript Mongo Shell :

db.logs.find()

Here the same code with Java Mongo Driver :

package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindLogsWithMongoJavaDriver_0 {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// Find all DB object from the DB collection
			DBObject log = null;
			DBCursor cursor = coll.find();
			
			// Loop for each db object of the cursor.
			while (cursor.hasNext()) {
				log = cursor.next();
				System.err.println(log.toString());
			}
		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

If you execute it, you will see in the console the following JSON stream :

{ "_id" : { "$oid" : "518d01813bfe01bef797d031"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}}
{ "_id" : { "$oid" : "518d01813bfe01bef797d032"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}}
...

You can notice a little difference JSON representation with Mongo Shell :

{ "_id" : ObjectId("518d01813bfe01bef797d031"), 
  "url" : "http://www.mongodb.org/", 
  "created" : ISODate("2013-05-10T14:17:37.515Z") }
{ "_id" : ObjectId("518d01813bfe01bef797d032"), 
  "url" : "http://www.mongodb.org/", 
  "created" : ISODate("2013-05-10T14:17:37.515Z") }

It’s just the JSON representation which changes. For more information, please read MongoDB Extended JSON.

The Java JSON stream is not a valid JSON array (it miss the [] characters and , character between each JSON log.) The driver provides the com.mongodb.util.JSON helper which is used to serialize object as JSON. To generate a JSON array, replace the following code:

while (cursor.hasNext()) {
	log = cursor.next();
	System.err.println(log.toString());
}

with :

StringBuilder buf = new StringBuilder();
JSON.serialize(cursor, buf);
System.err.println(buf.toString());

Here the full Java code :

package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class FindLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// Find all DB object from the DB collection
			DBCursor cursor = coll.find();

			// Generate JSON array of the cursor.
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			System.err.println(buf.toString());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

If you execute this class, you will see the following JSON array stream, on the console :

[ 
{ "_id" : { "$oid" : "518d01813bfe01bef797d031"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}} , 
{ "_id" : { "$oid" : "518d01813bfe01bef797d032"} , 
  "url" : "http://www.mongodb.org/" , 
  "created" : { "$date" : "2013-05-10T14:17:37.515Z"}} ,
...]

RemoveLogsWithMongoJavaDriver.java

In the [step0], we have removed all logs with the following Javascript Mongo Shell :

db.logs.remove()

Here the same code with Java Mongo Driver :

package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class RemoveLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// remove all logs
			coll.remove(new BasicDBObject());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

FindPaginatedLogsWithMongoJavaDriver.java

In the [step0], we have displayed paginated logs with the following Javascript Mongo Shell :

var pageIndex = 0;
var pageSize = 5;
db.logs.find().skip(pageIndex).limit(pageSize);

Here the same code with Java Mongo Driver :

package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class FindPaginatedLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection coll = db.getCollection("logs");

			// Find paginated DB object from the DB collection
			int pageIndex = 0;
			int pageSize = 5;
			DBCursor cursor = coll.find().skip(pageIndex).limit(pageSize);

			// Generate JSON array of the cursor.
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			System.err.println(buf.toString());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

Pojo Mapper MongoJack

Pojo Mapper gives you the capability to use Pojo instead of using Mongo DBObject. It follows the same idea than JPA.

It exists several Pojo Mapper that you can see here.

There are not a specification for Pojo Mapper Mongo (compared to JPA), so each Pojo Mapper provides their annotations to map the Pojo fields with Mongo JSON properties.

The whole Pojo Mappers uses the Mongo Java Driver.

I have choosen to use MongoJack as Pojo Mapper in my article because I think it’s the more fast than other Pojo Mappers. Indeed, it implements their own com.mongodb.DBDecoder (see org.mongojack.internal.stream.JacksonDBDecoder).

The other Pojo Mapper that I have studied uses the default DBDecoder of the driver : the pojo mapper uses this decoder to get DBObject and build a Pojo from this DBObject. With Mongojack, the JacksonDBDecoder creates directly the Pojo without creating an instance of DBObject.

Download MongoJack

To download MongoJack, I have used this maven dependency :

<dependency>
	<groupId>org.mongojack</groupId>
	<artifactId>mongojack</artifactId>
	<version>2.0.0-RC5</version>
</dependency>

Pojo Log

To use the Pojo Mapper Mongojack, we need to create a Pojo Log like this:

package org.samples.mongodb.operations.pojomapper.mongojack;

import java.util.Date;

import javax.persistence.Id;

public class Log {

	@Id
	private String id;

	private String url;
	private Date created;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

}

You can notice that the annotation javax.persistence.Id is used to map it with ObjectId.

InsertLogsWithMongoJack

Here the code to insert logs with Pojo Mapper Mongojack :

package org.samples.mongodb.operations.pojomapper.mongojack;

import java.net.UnknownHostException;
import java.util.Calendar;

import org.mongojack.JacksonDBCollection;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class InsertLogsWithMongoJack {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection dbColl = db.getCollection("logs");

			// Use Pojo Mapper MongoJack
			JacksonDBCollection<Log, String> coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Insert logs with Pojo Log
			Log log = null;
			for (int i = 0; i < 100; i++) {
				log = new Log();
				log.setUrl("http://mongojack.org/");
				log.setCreated(Calendar.getInstance().getTime());
				coll.insert(log);
			}

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

FindLogsWithMongoJack

Here the code to find total logs with Pojo Mapper Mongojack :

package org.samples.mongodb.operations.pojomapper.mongojack;

import java.io.IOException;

import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindLogsWithMongoJack {

	public static void main(String[] args) throws JsonGenerationException,
			JsonMappingException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection dbColl = db.getCollection("logs");

			// Use Pojo Mapper MongoJack
			JacksonDBCollection<Log, String> coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Find all Pojo Log from the MongoJack collection
			DBCursor<Log> cursor = coll.find();

			// Serialize list of Log as JSON
			ObjectMapper om = new ObjectMapper();
			om.writer().writeValue(System.err, cursor.toArray());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

RemoveLogsWithMongoJack

Here the code to remove total logs with Pojo Mapper Mongojack :

package org.samples.mongodb.operations.pojomapper.mongojack;

import java.net.UnknownHostException;

import org.mongojack.JacksonDBCollection;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class RemoveLogsWithMongoJack {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection dbColl = db.getCollection("logs");

			// Use Pojo Mapper MongoJack
			JacksonDBCollection<Log, String> coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// remove all logs
			coll.remove(new BasicDBObject());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

FindPaginatedLogsWithMongoJack

Here the code to return paginated logs with Pojo Mapper Mongojack :

package org.samples.mongodb.operations.pojomapper.mongojack;

import java.io.IOException;

import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindPaginatedLogsWithMongoJack {

	public static void main(String[] args) throws JsonGenerationException,
			JsonMappingException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				"mongodb://localhost:27017");
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get "logs" collection from the "websites" DB.
			DB db = mongo.getDB("websites");
			DBCollection dbColl = db.getCollection("logs");

			// Use Pojo Mapper MongoJack
			JacksonDBCollection<Log, String> coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Find paginated Pojo Log from the MongoJack collection
			int pageIndex = 0;
			int pageSize = 5;
			DBCursor<Log> cursor = coll.find().skip(pageIndex).limit(pageSize);

			// Serialize list of Log as JSON
			ObjectMapper om = new ObjectMapper();
			om.writer().writeValue(System.err, cursor.toArray());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}

Conclusion

In this article we have seen how to manage with Java code basic mongo operations (insert, remove etc) with Mongo Java Driver and Pojo Mapper. Pojo Mapper requires to create a Pojo.

In the next article [step2], we will use Mongo in a JEE Servlet.

About these ads
Catégories:Dojo, Mongo JEE, MongoDB
  1. Pas encore de commentaire.
  1. mai 10, 2013 à 3:57  
  2. mai 11, 2013 à 11:16  
  3. mai 14, 2013 à 12:47  
  4. mai 14, 2013 à 1:17  
  5. mai 14, 2013 à 10:43  

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

Suivre

Recevez les nouvelles publications par mail.

Rejoignez 169 autres abonnés

%d bloggers like this: