I've been in the world of software development for 14+ years working with most mainstream programming languages at some point. Chad is a DZone MVB and is not an employee of DZone and has posted 38 posts at DZone. You can read more from them at their website. View Full User Profile

Build a Spring-Data project with MongoDB in under 5 minutes using Netbeans 7 and Maven

11.03.2011
| 8845 views |
  • submit to reddit

Spring-Data is a rapidly moving project and has support for many technologies such as non-relational databases, map-reduce frameworks, and cloud based data services as well as providing support for relational databases. Today I’m going to focus on their support for MongoDB.


Note: I’m going to borrow the starter code from the Spring-Data documentation. I will be changing the version from M3 to M4 however and the current Spring-Data documentation is assuming M3 (as of the date of this article) and it looks like they did some namespace changes from M3 to M4 so I’m fixing that in the code for this article. By the time you read this however the documentation on their site might be updated to M4 or newer.

I am using Netbeans 7 with the Maven support to build and run the project.

With Netbeans create a new Maven Java Application called: SpringDataMongoDB

Modify the pom.xml to include the following new repository:

<repositories>
  <repository>
    <id>spring-milestone</id>
    <name>Spring Maven MILESTONE Repository</name>
    <url>http://maven.springframework.org/milestone</url>
  </repository>
</repositories>

We need to add one dependency to the pom.xml as well:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.0.0.M4</version>
</dependency>

My full POM file looks like this:

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.giantflyingsaucer</groupId>
    <artifactId>SpringDataMongoDB</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>SpringDataMongoDB</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <repositories>
        <repository>
            <id>spring-maven-release</id>
            <name>Spring Maven Release Repository</name>
            <url>http://maven.springframework.org/release</url>
        </repository>
        <repository>
            <id>spring-maven-milestone</id>
            <name>Spring Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.0.0.M4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

When Netbeans generates the new project it will by default create a file called: App.java

Modify the App.java file as follows:

package com.giantflyingsaucer;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
import com.mongodb.Mongo;
 
import java.net.UnknownHostException;
 
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
 
public class App
{
    private static final Log log = LogFactory.getLog(App.class);
 
    public static void main( String[] args )
    {
        try {
            MongoOperations mongoOps = new MongoTemplate(new Mongo(), "mydb");
            mongoOps.insert(new Person("Joe", 34));
            log.info(mongoOps.findOne(new Query(Criteria.where("name").is("Joe")), Person.class));
            mongoOps.dropCollection("person");
        }
        catch(UnknownHostException ex) {
            log.error(ex.getMessage());
        }
    }
}

With Netbeans right-click on the project and add new class called: Person

The Person.java code is a very simple POJO:

package com.giantflyingsaucer;
 
public class Person {
 
  private String id;
  private String name;
  private int age;
 
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
 
  public String getId() {
    return id;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
 
  @Override
  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
  }
}

Add a log4j.properties file to the resources folder. Here is the one that the Spring documentation suggests as a start:

log4j.rootCategory=INFO, stdout
 
log4j.appender.stdout=org.springframework.data.document.mongodb.log4j.MongoLog4jAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.stdout.host = localhost
log4j.appender.stdout.port = 27017
log4j.appender.stdout.database = logs
log4j.appender.stdout.collectionPattern = %X{year}%X{month}
log4j.appender.stdout.applicationId = my.application
log4j.appender.stdout.warnOrHigherWriteConcern = FSYNC_SAFE
 
log4j.category.org.apache.activemq=ERROR
log4j.category.org.springframework.batch=DEBUG
log4j.category.org.springframework.data.document.mongodb=DEBUG
log4j.category.org.springframework.transaction=INFO

My final project structure looks like the following:

With Maven do a Clean and Build on the project (you can do this in Netbeans 7 by right-clicking on the project and selecting that option).

At this point you need to get MongoDB running, check out the docs on how to do that and when it’s running on your computer follow the final step below.

With MongoDB started you can now run the project.

Expected results:

[exec:exec]
Oct 30, 2011 9:18:14 PM com.giantflyingsaucer.App main
INFO: Person [id=4eae056603640e4e098501f7, name=Joe, age=34]

 

From http://www.giantflyingsaucer.com/blog/?p=3363

Published at DZone with permission of Chad Lung, author and DZone MVB.

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

Tags: