NoSQL Zone is brought to you in partnership with:

Highly motivated Senior Java/JEE Software Developer with 7+ years of solid industry experience. Excellent team player with an experience working in distributed international teams, using Agile/Scrum methodology. Artur has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Spring Data & MongoDB

08.28.2011
| 27726 views |
  • submit to reddit

 In this article we are going to cover the following topics:

  1. MongoDB Installation on Windows Machine.
  2. MongoDB Java Example.
  3. Spring Data & MongoDB.

  MongoDB Installation on Windows Machine:

     Download MongoDB from official MongoDB website.

     Unzip MongoDB files to your prefer location, for example : “D:\mongodb-win32-x86_64-1.8.3“.

     MongoDB won’t create data directory automatically. You need to create a data directory for MongoDB, for example : “D:\mongodb-data“.

    mongod.exe is the database server daemon, run it and point it to the data directory, via “--dbpath” argument.

  D:\mongodb-win32-x86_64-1.8.3\bin>mongod --dbpath "D:\mymongodb-data" 

   In the output, you will notice that MongoDB started a web admin interface listening on port 28017.

   To access it, just type http://your-ipaddress:28017.

   In order to connect to your MongoDB server type D:\mongodb-win32-x86_64-1.8.3\bin>mongo

   If you are able to view the MongoDB web admin interface and also connected to the database server via mongo.exe, then your MongoDB is installed on the Windows successfully.

 

  MongoDB Java Example:

    A simple Java MongoDB example.

    Technologies and tools used:

  1. MongoDB 1.8.3
  2. MongoDB-Java-Driver 2.6.5
  3. JDK 1.6
 
package edu.seua.mongo;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
* Java MongoDB Example
*
*/
public class MongoApp {

public static void main(String[] args) {

try {
// connect to mongoDB
Mongo mongo = new Mongo("localhost", 27017);

// if database doesn't exists, mongoDB will create it
DB db = mongo.getDB("mydb");

// Get collection from MongoDB, database named "mydb"
// if collection doesn't exists, mongoDB will create it
DBCollection collection = db.getCollection("myCollection");

// create a document to store attributes
BasicDBObject document = new BasicDBObject();
document.put("id", 100);
document.put("name", "simple name");
document.put("message", "simple message");


// save it into collection named "myCollection"
collection.insert(document);

// search query
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", 100);

DBCursor cursor = collection.find(searchQuery);

// loop over the cursor and display the result
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}

 

Output

{ 
"_id" : { "$oid" : "4e5936ca602fbf0c50e0c9d0"} ,
"id" : 100 , "name" : "simple name" , "message" : "simple message"
}

 

   Now it's time for Spring Data & MongoDB:

    Technologies and jars used:

  1. MongoDB 1.8.3
  2. JDK 1.6
  3. mongo-2.6.5.jar
  4. org.springframework.context-3.0.5.RELEASE.jar
  5. org.springframework.core-3.0.5.RELEASE.jar
  6. org.springframework.beans-3.0.5.RELEASE.jar
  7. commons-logging-1.1.1.jar
  8. org.springframework.asm-3.0.5.RELEASE.jar
  9. spring-data-mongodb-1.0.0.M2.jar
  10. slf4j-api-1.6.1.jar
  11. slf4j-jdk14-1.6.1.jar
  12. spring-dao-2.0.8.jar
  13. spring-expression-3.1.0.M2.jar
  14. spring-data-commons-core-1.1.0.M1.jar
  15. spring-tx-3.1.0.M1.jar
  16. spring-data-document-core-1.0.0.M2.jar

Spring XML configuration file (mongo-config.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<mongo:mongo host="localhost" port="27017" />

<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="myNewdb" />
<constructor-arg name="defaultCollectionName" value="myNewCollection" />
</bean>

<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
<context:annotation-config />

</beans>

  Let's create Employee DTO

package edu.seua.mongo;

public class Employee {

private String id;
private String firstname;
private String lastname;
private int age;

public Employee() {
}

public Employee(String id, String firstname, String lastname, int age) {
super();
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}

public String getId() {
return id;
}

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

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Employee [age=" + age + ", firstname=" + firstname + ", id="
+ id + ", lastname=" + lastname + "]";
}

}



  Full Example   

    Full example shows you how to use Spring data to perform CRUD operations in mongoD.

    The employee object is saved into a collection named employees.

package edu.seua.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;

/**
* Java Spring Data & MongoDB Example
*
*/
public class SpringDataMongoApp {

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext("edu/seua/mongo/mongo-config.xml");

MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

Employee employee = new Employee("100", "firstName", "lastName", 23);

// save
mongoOperation.save("employees", employee);

// find
Employee savedEmployee = mongoOperation.findOne("employees", new Query(Criteria.where(
"id").is("100")), Employee.class);

System.out.println("Saved Employee: " + savedEmployee);

// update
mongoOperation.updateFirst("employees", new Query(Criteria.where(
"firstname").is("firstName")), Update.update("lastname",
"new lastName"));

// find
Employee updatedEmployee = mongoOperation.findOne("employees", new Query(
Criteria.where("id").is("100")), Employee.class);

System.out.println("Updated Employee: " + updatedEmployee);

// delete
mongoOperation.remove("employees", new Query(Criteria.where("id").is(
"100")), Employee.class);

// List
List<Employee> listEmployee = mongoOperation.getCollection("employees", Employee.class);
System.out.println("size of employees = " + listEmployee.size());

}
}

 

  Output

Saved Employee: Employee [age=23, firstname=firstName, id=100, lastname=lastName]
Updated Employee: Employee [age=23, firstname=firstName, id=100, lastname=new lastName]
size of employees = 0

 

Legacy
Article Resources: 
Published at DZone with permission of its author, Artur Mkrtchyan.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)