[Spring Data Mongo一]Spring Mongo Template操作MongoDB

什么是Spring Data Mongo

Spring Data MongoDB项目对访问MongoDB的Java客户端API进行了封装,这种封装类似于Spring封装Hibernate和JDBC而提供的HibernateTemplate和JDBCTemplate,主要能力包括

1. 封装客户端跟MongoDB的链接管理

2. 文档-对象映射,通过注解:@Document(collection="collectionName")

3.对模版式的代码,进行了封装,类似于JDBCTemplate和HibernateTemplate

 

Spring Data Mongo在Spring中的基本配置

 

<?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: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-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <mongo:mongo replica-set="localhost:27018,localhost:27017,localhost:27019">
        <mongo:options connections-per-host="200"
                       threads-allowed-to-block-for-connection-multiplier="100"
                       connect-timeout="1000"
                       max-wait-time="1500"
                       auto-connect-retry="true"
                       socket-keep-alive="true"
                       socket-timeout="1500"
                       slave-ok="true"
                       write-number="1"
                       write-timeout="0"
                       write-fsync="true"/>
    </mongo:mongo>
    <mongo:db-factory dbname="foolbar" username="" password="" mongo-ref="mongo"/>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
</beans>

 说明:

1.其中的mongoTemplate是客户端操作MongoDB的主要类,它包含了增删改查功能以及其它一些操作,这些操作在以后的篇幅中会讲到

2.replica-set是副本集集群的MongoDB服务器的链接地址,以逗号分开,如果仅有一台服务器,使用host="localhost:27017”或者replica-set="localhost:27017"都可以,

3.mongo:options定义了链接属性和读写相关属性,以后再来完善这部分

 

Document和Collection注解

 

package com.tom.user.model;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {
    @Id
    private ObjectId userId;
    private String name;
    private String passwd;

    public ObjectId getUserId() {
        return userId;
    }

    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
}

 上面的代码定义了一个类似于Hibernate实体Bean的POJO,在Hibernate它可以和数据库的一个表建立映射关系,但是在MongoDB中,一个集合中的文档的Field是任意的,因此POJO必须映射到文档一级(@Document),同时注解中指明这个文档属于哪个集合(一个文档只能属于一个集合)。当使用MongoDBTemplate对POJO进行操作时,可以根据POJO的类型得到它要往那个集合中写文档

 

 MongoDBTemplate简单CRUD操作

 

package com.tom.user.storage;

import com.tom.user.model.User;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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.data.mongodb.core.query.Update;

import java.util.List;

/*
http://www.tuicool.com/articles/EFnyye
http://www.mkyong.com/mongodb/spring-data-mongodb-hello-world-example/

 */
public class UserMongoDBStorageServiceTest2 {

    private ApplicationContext cxt  = null;

    @Before
    public void setup() {
        cxt = new ClassPathXmlApplicationContext("applicationContext.xml");

    }

    private void create() {
        drop();
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        User user = new User();
        user.setName("abc");
        user.setPasswd("def");
        template.insert(user);
    }

    public void query() {
        Query query = new Query(new Criteria("name").is("abc"));
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        List<User> users = template.find(query, User.class);
        Assert.assertEquals(1, users.size());
        User user = users.get(0);
        Assert.assertEquals("abc", user.getName());
        Assert.assertEquals("def", user.getPasswd());
    }

    public void update() {
        Query query = new Query(new Criteria("name").is("abc"));
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        List<User> users = template.find(query, User.class);
        Assert.assertEquals(1, users.size());
        User user = users.get(0);
        user.setPasswd("def-updated");
        Update update = new Update();
        update.set("passwd",user.getPasswd());
        template.updateFirst(query, update, User.class);

        Assert.assertEquals("abc", user.getName());
    }

    public void queryUpdate() {
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        List<User> users = template.findAll(User.class);
        Assert.assertEquals(1, users.size());
        User user = users.get(0);
        Assert.assertEquals("abc", user.getName());
        Assert.assertEquals("def-updated",user.getPasswd());
    }

    public void drop() {
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        template.dropCollection(User.class);
    }

    @org.junit.Test
    public void testCRUD() {
        create();
        query();
        update();
        queryUpdate();
        drop();
    }
}

 

 

只对Update操作做下说明:

 

 

    public void update() {
        Query query = new Query(new Criteria("name").is("abc"));
        MongoTemplate template = cxt.getBean("mongoTemplate", MongoTemplate.class);
        List<User> users = template.find(query, User.class);
        Assert.assertEquals(1, users.size());
        User user = users.get(0);
        user.setPasswd("def-updated");
        Update update = new Update();
        update.set("passwd",user.getPasswd());
        template.updateFirst(query, update, User.class);

        Assert.assertEquals("abc", user.getName());
    }

 

 

User两个字段name和passwd,Update中只通过Update.set方法对passwd进行了更改,那么name这个属性在更新操作完成后是从文档中被删除了还是保留下来了?答案是保留下来了,并且值保持不变,这就为更新操作提供了很大的便利性,要改什么就在Update中指定什么,

 

Spring Data Mongo连接MongoDB服务器的参数

 

你可能感兴趣的:(template)