mongodb and spring

本文介绍如何使用NetBeans 7和Maven在五分钟内建立一个基于Spring Data的MongoDB项目。文中详细展示了配置POM文件、创建实体类及进行基本CRUD操作的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Post to Twitter

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值