环境:

SpringMVC项目搭建

1、使用Spring-Data整合Mongodb

1.1、添加Spring-Data依赖

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.8.1.RELEASE</version>
</dependency>

1.2、创建mongodb配置文件

创建文件mongodb.properties

mongo.hostport=127.0.0.1:27017
mongo.dbname=SpringMVC_demo
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
#Socket超时时间
mongo.socketTimeout=1500
mongo.slaveOk=true

1.3、配置mongodb映射

在springMVC.xml文件中加入如下配置:

<!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongodb.properties" />
<!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
<mongo:mongo id="mongo" replica-set="${mongo.hostport}">
    <!-- 一些连接属性的设置 -->
    <mongo:options
    threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
    connect-timeout="${mongo.connectTimeout}" 
    max-wait-time="${mongo.maxWaitTime}" 
    auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" 
    socket-timeout="${mongo.socketTimeout}" 
    slave-ok="${mongo.slaveOk}" 
    write-number="1" 
    write-timeout="0" 
    write-fsync="true" />
</mongo:mongo>
<mongo:db-factory dbname="database" mongo-ref="mongo" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongo" />
    <constructor-arg name="databaseName" value="${mongo.dbname}" />
</bean>

此处需要加入规范文件

<beans 
...
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
...
xsi:schemaLocation="
...
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
...
">
...
</beans>

1.4、实现DAO

实体类:

package com.celloud.model;

import java.util.Date;

public class Student {
    private Integer id;

    private String code;

    private String name;

    private Integer age;

    private Date birthday;

    public Integer getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

DAO接口:

package com.celloud.dao;

import com.celloud.model.Student;

public interface StudentDao {

    public void insert(Student student);

    public Student getById(int id);
    public int removeAll();
}

DAO实现:

package com.celloud.dao.impl;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.celloud.dao.StudentDao;
import com.celloud.model.Student;
@Service("studentDaoInSpringData")
public class StudentDaoInSpringData implements StudentDao {
    @Resource
    private MongoTemplate mongoTemplate;  
    @Override
    public void insert(Student student) {
        mongoTemplate.save(student);
    }

    @Override
    public Student getById(int id) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), Student.class);
    }
    @Override
    public int removeAll() {
        return mongoTemplate.findAllAndRemove(new Query(), Student.class).size();
    }

}

1.5、单元测试

建立单元测试类:

package com.celloud.dao.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.celloud.dao.StudentDao;
import com.celloud.model.Student;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:springMVC.xml" })
public class StudentDaoTest {
    @Resource
    private StudentDao studentDao;
    @Test
    public void test() {
        System.out.println(studentDao.removeAll());
        Student stu = new Student();
        stu.setAge(19);
        stu.setBirthday(new Date());
        stu.setCode("1001");
        stu.setId(1);
        stu.setName("张三");
        studentDao.insert(stu);
        Student stu2 = studentDao.getById(1);
        System.out.println(stu2.getCode().equals(stu.getCode()));
    }
}

/src/main/resources中的配置文件复制到/src/test/resources

运行单元测试,无异常则表示成功

2、使用Morphia整合Mongodb

2.1、还原1的配置

还原pom.xml文件中的依赖

还原springMVC.xml文件中mongo相关配置

注释dao实现类的相关代码

将mongodb.properties文件修改为:

mongo.host=127.0.0.1
mongo.port=27017
mongo.database=SpringMVC_demo
mongo.username=
mongo.password=

用户名密码如果没有可不写

2.2、加入依赖

加入Morphia相关依赖

<!-- Spring 使用Morphia整合mongodb -->
<dependency>
    <groupId>org.mongodb.morphia</groupId>
    <artifactId>morphia</artifactId>
    <version>1.0.1</version>
</dependency>
<!-- mongodb的驱动,Morphia需依赖 -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.13.0</version>
</dependency>

2.3、配置mongodb相关的bean

在springMVC.xml文件中添加如下配置:

<bean id="mongoServerAddress" class="com.mongodb.ServerAddress">
    <constructor-arg value="${mongo.host}" />
    <constructor-arg value="${mongo.port}" />
</bean>
<!-- 如果没有启用mongodb的用户验证,可不使用此配置 -->
<!-- <bean id="mongoCredential" class="com.mongodb.MongoCredential" factory-method="createCredential"> 
    构造Credential的方法的参数,顺序不能改变 <constructor-arg value="${mongo.username}" /> <constructor-arg 
    value="${mongo.database}" /> <constructor-arg value="${mongo.password}" /> 
    </bean> -->
<bean id="mongoClient" class="com.mongodb.MongoClient"
    destroy-method="close">
    <constructor-arg ref="mongoServerAddress" />
    <!-- <constructor-arg> <list> <ref bean="mongoCredential" /> </list> </constructor-arg> -->
</bean>
<bean id="morphia" class="org.mongodb.morphia.Morphia" />
<bean id="datastore" class="org.mongodb.morphia.Datastore"
    factory-bean="morphia" factory-method="createDatastore">
    <constructor-arg ref="mongoClient" />
    <constructor-arg value="${mongo.database}" />
</bean>

2.3、实现DAO

实体类及DAO接口如1.4

DAO实现类:

package com.celloud.dao.impl;

import javax.annotation.Resource;

import org.mongodb.morphia.Datastore;

import com.celloud.dao.StudentDao;
import com.celloud.model.Student;

public class StudentDaoInMorphia implements StudentDao {
    @Resource
    private Datastore dataStore;
    @Override
    public void insert(Student student) {
        dataStore.save(student);
    }

    @Override
    public Student getById(int id) {
        return dataStore.createQuery(Student.class).field("id").equal(id).get();
    }
    @Override
    public int removeAll() {
        Query<Student> query = dataStore.createQuery(Student.class);
        return dataStore.delete(query).getN();
    }
}

2.4、单元测试

单元测试类直接使用1.5中的单元测试类即可。

/src/main/resources中的配置文件复制到/src/test/resources中,运行单元测试,无异常则成功。