`

Spring Data - MongoDB 教程 (1.0.0.M1)

阅读更多
Spring Data - MongoDB 教程(1.0.0.M1)

在这个教程中,我们将对一个存在的Spring MVC 3 - MongoDB进行重构,使用最新公布 Spring Data Document 1.0.0.M1 for MongoDB。 我们的目的是了解Spring data MongoDB ,简化开发。去领会 spring data。适当的去了解怎么用mongoDB进行CRUD ,这是我为什么去重构一个已有的项目
What is MongoDB?
MongoDB是一个基于分布式文件存储的数据库开源项目。由C++语言编写。旨在为WEB应用提供可护展的高性能数据存储解决方案。

它的特点是高性能、易部署、易使用,存储数据非常方便。主要功能特性有:
*面向集合存储,易存储对象类型的数据。
*模式自由。
*支持动态查询。
*支持完全索引,包含内部对象。
*支持查询。
*支持复制和故障恢复。
*使用高效的二进制数据存储,包括大型对象(如视频等)。
*自动处理碎片,以支持云计算层次的扩展性
*支持RUBY,PYTHON,JAVA,C++,PHP等多种语言。
*文件存储格式为BSON(一种JSON的扩展)
*可通过网络访问

所谓“面向集合”(Collenction-Orented),意思是数据被分组存储在数据集中,被称为一个集合(Collenction)。每个集合在数据库中都有一个唯一的标识名,并且可以包含无限数目的文档。集合的概念类似关系型数据库(RDBMS)里的表(table),不同的是它不需要定义任何模式(schema)。模式自由(schema-free),意味着对于存储在mongodb数据库中的文件,我们不需要知道它的任何结构定义。如果需要的话,你完全可以把不同结构的文件存储在同一个数据库里。存储在集合中的文档,被存储为键-值对的形式。键用于唯一标识一个文档,为字符串类型,而值则可以是各中复杂的文件类型。我们称这种存储形式为BSON(Binary Serialized dOcument Format)。

MongoDB服务端可运行在Linux、Windows或OS X平台,支持32位和64位应用,默认端口为27017。推荐运行在64位平台,因为MongoDB在32位模式运行时支持的最大文件尺寸为2GB。

Source: http://www.mongodb.org/
关于 Spring Data - Document
Spring Data Document 框架可以使spring Document数据库操作应用更简单。
The Spring Data Document (or DATADOC) framework makes it easy to write Spring applications that use a Document store by eliminating the redundant tasks and boiler place code required for interacting with the store through Spring's excellent infrastructure support.

Source: Spring Datastore Document - Reference Documentation
In a nutshell MongoDB uses JSON instead of SQL There's no static schema to create. All schemas are dynamic, meaning you create them on-the-fly. You can try a real-time online shell for MongoDB at http://try.mongodb.org/. Visit the official MongoDB site for a thorough discussion.

Prerequisites
In order to complete this tutorial, you will be required to install a copy of MongoDB. If you don't have one yet, grab a copy now by visiting http://www.mongodb.org/display/DOCS/Quickstart. Installation is really easy.

Development
Our application is a simple CRUD system for managing a list of Persons. Data is stored in MongoDB database. We'll start by declaring our domain objects. Then we'll discuss the service layer. And lastly we'll add the controllers.

Domain层
我们的应用定义了一个唯一的类 Person,他有一下属性:
pid
firstName
lastName
money


Our application contains a single domain object named Person. It consists the following properties:

下面是类的定义:

Person.java

package org.krams.tutorial.domain;

import java.io.Serializable;

/**
 * A simple POJO representing a Person
 * 一个简单的POJO
 * @author Krams 
 */
public class Person implements Serializable {

 private static final long serialVersionUID = -5527566248002296042L;
 
 private String pid;
 private String firstName;
 private String lastName;
 private Double money;

 public String getPid() {
  return pid;
 }

 public void setPid(String pid) {
  this.pid = pid;
 }

 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 Double getMoney() {
  return money;
 }

 public void setMoney(Double money) {
  this.money = money;
 }
}


注意:
我们通常使用id作为Person的一个属性,但在本教程中我们使用了一个Pid代替了id,这是因为我们在用spring data的时候,它将打乱属性id与mongoDB内置的_id。
现在,如果你要使用Spring-data 不要使用Id属性,选择一个不同的名称以代替id。

Service 层
我们的 service 类包含了在原生应用程序的主要改变 。而不是调用本地mongodb方法进行增删改查,我们使用的数据Spring Data的 MongoTemplate来代替他。



MongoTemplate是什么
MongoTemplate提供方便的方法让MongoDB的JSON文件和你的类之间的自动映射。开箱,MongoTemplate使用基于Java的默认转换器,但你也可以写自己的转换器,用于读取和存储类及其他操作。
资料来源:Spring Datastore Document - Reference Documentation

Service:

PersonService.java

package org.krams.tutorial.service;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.krams.tutorial.domain.Person;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.data.document.mongodb.query.Criteria.where;

/**
 * Service for processing {@link Person} objects.
 * Uses Spring's {@link MongoTemplate} to perform CRUD operations.
 * 
 * For a complete reference to MongoDB
 * see http://www.mongodb.org/
 * 
 * For a complete reference to Spring Data MongoDB 
 * see http://www.springsource.org/spring-data
 * 
 * @author Krams at {@link http://krams915@blogspot.com}
 */
@Service(personService)
@Transactional
public class PersonService {

 protected static Logger logger = Logger.getLogger(service);
 
 @Resource(name=mongoTemplate)
 private MongoTemplate mongoTemplate;
 
 /**
  * 获取所有的 person
  */
 public List getAll() {
  logger.debug(Retrieving all persons);
 
  // 查找一个属性(pid)存在的条目
        Query query = new Query(where(pid).exists(true));
      
        //执行查询,查找所有的存在的Person条目
        List persons = mongoTemplate.find(query, Person.class);
        
  return persons;
 }
 
 /**
  * 获取一个 person
  */
 public Person get( String id ) {
  logger.debug(Retrieving an existing person);
  
  // 获取一个pid匹配id的条目
        Query query = new Query(where(pid).is(id));
        // 执行查询,并找到一个匹配的条目 
        Person person = mongoTemplate.findOne(mycollection, query, Person.class);
     
  return person;
 }
 
 /**
  * 添加一个新的person
  */
 public Boolean add(Person person) {
  logger.debug(Adding a new user);
  
  try {
   
   //设置一个新值的PID(UUID)
   person.setPid(UUID.randomUUID().toString());
   // 插入到DB
      mongoTemplate.insert(mycollection, person);

   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to add new user,e);
   return false;
  }
 }
 
 /**
  * 删除一个存在的person
  */
 public Boolean delete(String id) {
  logger.debug(Deleting existing person);
  
  try {
   
        // 获取一个pid匹配id的条目
         Query query = new Query(where(pid).is(id));
         // 运行查询和删除条目  
         mongoTemplate.remove(query);
         
   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to delete new user, e);
   return false;
  }
 }
 
 /**
  *编辑一个存在的Persn
  */
 public Boolean edit(Person person) {
  logger.debug(Editing existing person);
  
  try {
   
   // 获取一个pid匹配id的条目
         Query query = new Query(where(pid).is(person.getPid()));
         
   // 声明一个更新的对象。
         // 此相匹配的更新修饰符在MongoDBThis matches the update modifiers available in MongoDB
       Update update = new Update();
         
         update.set(firstName, person.getFirstName());
         mongoTemplate.updateMulti(query, update);
         
         update.set(lastName, person.getLastName());
         mongoTemplate.updateMulti(query, update);
         
         update.set(money, person.getMoney());
         mongoTemplate.updateMulti(query, update);
         
   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to edit existing user, e);
   return false;
  }
  
 }
}


该代码应该是很容易就能看懂的。请注意Spring数据如何减少代码量 。为了能更好的理解这种差异,让我们做个传统的MongoDB的和使用 SpringData数据检索的比较
检索所有的数据
传统的MongoDB实现

public List getAll() {
  logger.debug(Retrieving all persons);
   
  // 获取到集合
  DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);
  // 为了遍历数据记录获取到游标 
     DBCursor cur = coll.find();
     // 创建一个新的List
  List items = new ArrayList();
  // 遍历游标
        while(cur.hasNext()) {
         // 建立从 DBOject 到 Person的关系
         DBObject dbObject = cur.next();
         Person person = new Person();
          
         person.setId(dbObject.get(id).toString());
         person.setFirstName(dbObject.get(firstName).toString());
         person.setLastName(dbObject.get(lastName).toString());
         person.setMoney(Double.valueOf(dbObject.get(money).toString()));
 
         // 添加到新的List
         items.add(person);
        }
         
        // Return list
  return items;
 }


通过Spring Data的实现

public List getAll() {
  logger.debug(Retrieving all persons);
 
        Query query = new Query(where(pid).exists(true));
        List persons = mongoTemplate.find(query, Person.class);
        
  return persons;
 }


检索一个条目
传统的MongoDB实现

public Person get( String id ) {
  logger.debug(Retrieving an existing person);
   
  // 获取集合
  DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);
  // 创建一个新的对象
  DBObject doc = new BasicDBObject();
  //用ID来搜索
        doc.put(id, id);
         
        // 查找,并返回给定ID对应的人
        DBObject dbObject = coll.findOne(doc);
         
        // 建立从 DBOject 到 Person的关系
     Person person = new Person();
     person.setId(dbObject.get(id).toString());
     person.setFirstName(dbObject.get(firstName).toString());
     person.setLastName(dbObject.get(lastName).toString());
     person.setMoney(Double.valueOf(dbObject.get(money).toString()));
      
        // Return person
  return person;
 }


通过Spring Data的实现

public Person get( String id ) {
  logger.debug(Retrieving an existing person);
  
  // 查找一个条目,其中PID相匹配的ID
        Query query = new Query(where(pid).is(id));
        // 执行查询,并找到一个匹配的条目
        Person person = mongoTemplate.findOne(mycollection, query, Person.class);
     
  return person;
 }


添加一个Person
传统的MongoDB实现

public Boolean add(Person person) {
  logger.debug(Adding a new user);
   
  try {
   // 获取集合
   DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);
   // 创建一个Object
   BasicDBObject doc = new BasicDBObject();
   //使用UUID 随机生成的ID
   // See http://en.wikipedia.org/wiki/Universally_unique_identifier
         doc.put(id, UUID.randomUUID().toString() ); 
         doc.put(firstName, person.getFirstName());
         doc.put(lastName, person.getLastName());
         doc.put(money, person.getMoney());
         //  保存
         coll.insert(doc);
          
   return true;
    
  } catch (Exception e) {
   logger.error(An error has occurred while trying to add new user, e);
   return false;
  }
 }


通过Spring Data的实现

public Boolean add(Person person) {
  logger.debug(Adding a new user);
  
  try {
   
   // 设置一个新值的PID(UUID)
   person.setPid(UUID.randomUUID().toString());
   // 保存到DB
      mongoTemplate.insert(mycollection, person);

   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to add new user, e);
   return false;
  }
 }

删除一个条目
传统的MongoDB实现
public Boolean delete(String id) {
  logger.debug(Deleting existing person);
   
  try {
   // 检索一个条目
   BasicDBObject item = (BasicDBObject) getDBObject( id );
   // 获取集合
   DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);
   // 删除检索到的条目
         coll.remove(item);
          
   return true;
    
  } catch (Exception e) {
   logger.error(An error has occurred while trying to delete new user, e);
   return false;
  }
 }

通过Spring Data的实现
public Boolean delete(String id) {
  logger.debug(Deleting existing person);
  
  try {
   
   // 通过id检索到一个Person
         Query query = new Query(where(pid).is(id));
         // 运行查询和删除
         mongoTemplate.remove(query);
         
   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to delete new user, e);
   return false;
  }
 }




更新一个条目
传统的MongoDB实现
public Boolean edit(Person person) {
  logger.debug(Editing existing person);
   
  try {
   // 检索一个条目
   BasicDBObject existing = (BasicDBObject) getDBObject( person.getId() );
    
   DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);
    
   // 创建一个新的对象
   BasicDBObject edited = new BasicDBObject();
   // 分配现有的属性
   edited.put(id, person.getId()); 
   edited.put(firstName, person.getFirstName());
   edited.put(lastName, person.getLastName());
   edited.put(money, person.getMoney());
   // 更新
         coll.update(existing, edited);
          
   return true;
    
  } catch (Exception e) {
   logger.error(An error has occurred while trying to edit existing user, e);
   return false;
  }
   
 }

 //通过Spring Data的实现
public Boolean edit(Person person) {
  logger.debug(Editing existing person);
  
  try {
   
   // 通过id查询数据
         Query query = new Query(where(pid).is(person.getPid()));
         
   // 声明一个更新对象
         // 此相匹配的更新修饰符在MongoDB 。This matches the update modifiers available in MongoDB
   Update update = new Update();
         
         update.set(firstName, person.getFirstName());
         mongoTemplate.updateMulti(query, update);
         
         update.set(lastName, person.getLastName());
         mongoTemplate.updateMulti(query, update);
         
         update.set(money, person.getMoney());
         mongoTemplate.updateMulti(query, update);
         
   return true;
   
  } catch (Exception e) {
   logger.error(An error has occurred while trying to edit existing user, e);
   return false;
  }
  
 }



配置
利用Spring's MongoTemplate 需要通过配置,它还需要引入mongodb数据库。我们定义一个XML配置,满足这些要求:

mongo-config.xml

注意我们使用他们的命名空间(namespace):
xmlns:mongo=http://www.springframework.org/schema/data/mongo

我们已经通过声明宣布一个mongodb数据库的引用:

然后我们宣布mongotemplate引用mongodb database,一个DB, 集合(mycollection):



最后, 我们声明一个 initService

initService的目的是预填充我们的 MongoDB的样本数据

下面是类的声明

InitService.java

package org.krams.tutorial.service;

import java.util.UUID;

import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.krams.tutorial.domain.Person;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * MongoDB的例子数据初始化 Service 
 * 
 * 一个完整的应用 MongoDB
 *  http://www.mongodb.org/
 * 
 *  http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html
 * 
 * @author Krams at {@link http://krams915@blogspot.com}
 */
@Transactional
public class InitService {

 protected static Logger logger = Logger.getLogger(service);
 
 @Resource(name=mongoTemplate)
 private MongoTemplate mongoTemplate;

 private void init() {
  // 填充我们的MongoDB数据库
  logger.debug(Init MongoDB users);
  
  // Drop 存在的 collection
  mongoTemplate.dropCollection(mycollection);
  
  // 创建一个新的对象
  Person p = new Person ();
  p.setPid(UUID.randomUUID().toString());
  p.setFirstName(John);
  p.setLastName(Smith);
  p.setMoney(1000.0);
  
  // 插入到DB
     mongoTemplate.insert(mycollection, p);

     // 创建一个新的对象
  p = new Person ();
  p.setPid(UUID.randomUUID().toString());
  p.setFirstName(Jane);
  p.setLastName(Adams);
  p.setMoney(2000.0);
  
  // 插入到db
     mongoTemplate.insert(mycollection, p);
        
     // 创建一个新的对象
  p = new Person ();
  p.setPid(UUID.randomUUID().toString());
  p.setFirstName(Jeff);
  p.setLastName(Mayer);
  p.setMoney(3000.0);
  
  // 插入到
     mongoTemplate.insert(mycollection, p);
 }
}

Controller 层
创建完成domain类和Service后,我们需要声明一个控制器controller 处理Web请求 。

MainController.java
package org.krams.tutorial.controller;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.krams.tutorial.domain.Person;
import org.krams.tutorial.service.PersonService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * 处理和检索人的请求 
 * 
 * @author Krams at {@link http://krams915@blogspot.com}
 */
@Controller
@RequestMapping(/main)
public class MainController {

 protected static Logger logger = Logger.getLogger(controller);
 
 @Resource(name=personService)
 private PersonService personService;
 
 /**
  * 处理和检索所有的All Person,并显示在JSP页面中 
  * 
  * @return the name of the JSP page
  */
    @RequestMapping(value = /persons, method = RequestMethod.GET)
    public String getPersons(Model model) {
     
     logger.debug(Received request to show all persons);
     
     // 获得所有的人,把调用委托给PersonService
     List persons = personService.getAll();
     
     // Attach persons to the Model
     model.addAttribute(persons, persons);
     
     // This will resolve to /WEB-INF/jsp/personspage.jsp
     return personspage;
 }
    
    /**
     * 检索,添加页面
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = /persons/add, method = RequestMethod.GET)
    public String getAdd(Model model) {
     logger.debug(Received request to show add page);
    
     // 创建新的Person,并添加到模型 
     // This is the formBackingOBject
     model.addAttribute(personAttribute, new Person());

     // This will resolve to /WEB-INF/jsp/addpage.jsp
     return addpage;
 }
 
    /**
     * 增加了一个新的Person,通过委托加工PersonService。 
     *显示一个确认JSP页面
     * @return  the name of the JSP page
     */
    @RequestMapping(value = /persons/add, method = RequestMethod.POST)
    public String add(@ModelAttribute(personAttribute) Person person) {
  logger.debug(Received request to add new person);
  
     // The personAttribute model has been passed to the controller from the JSP
     // We use the name personAttribute because the JSP uses that name
  
  // Call PersonService to do the actual adding
  personService.add(person);

     // This will resolve to /WEB-INF/jsp/addedpage.jsp
  return addedpage;
 }
    
    /**
     * Deletes an existing person by delegating the processing to PersonService.
     * Displays a confirmation JSP page
     * 
     * @return  the name of the JSP page
     */
    @RequestMapping(value = /persons/delete, method = RequestMethod.GET)
    public String delete(@RequestParam(value=pid, required=true) String id, 
              Model model) {
   
  logger.debug(Received request to delete existing person);
  
  // Call PersonService to do the actual deleting
  personService.delete(id);
  
  // Add id reference to Model
  model.addAttribute(pid, id);
     
     // This will resolve to /WEB-INF/jsp/deletedpage.jsp
  return deletedpage;
 }
    
    /**
     * Retrieves the edit page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = /persons/edit, method = RequestMethod.GET)
    public String getEdit(@RequestParam(value=pid, required=true) String id,  
              Model model) {
     logger.debug(Received request to show edit page);
    
     // Retrieve existing Person and add to model
     // This is the formBackingOBject
     model.addAttribute(personAttribute, personService.get(id));
     
     // This will resolve to /WEB-INF/jsp/editpage.jsp
     return editpage;
 }
    
    /**
     * Edits an existing person by delegating the processing to PersonService.
     * Displays a confirmation JSP page
     * 
     * @return  the name of the JSP page
     */
    @RequestMapping(value = /persons/edit, method = RequestMethod.POST)
    public String saveEdit(@ModelAttribute(personAttribute) Person person, 
                 @RequestParam(value=pid, required=true) String id, 
                Model model) {
     logger.debug(Received request to update person);
    
     // The personAttribute model has been passed to the controller from the JSP
     // We use the name personAttribute because the JSP uses that name
     
     // We manually assign the id because we disabled it in the JSP page
     // When a field is disabled it will not be included in the ModelAttribute
     person.setPid(id);
     
     // Delegate to PersonService for editing
     personService.edit(person);
     
     // Add id reference to Model
  model.addAttribute(pid, id);
  
     // This will resolve to /WEB-INF/jsp/editedpage.jsp
  return editedpage;
 }
    
}
Our controller is a simple class that delegates actual processing to PersonService. When the service is done processing, the controller forwards the result to a JSP view.

Other Configurations and Files
To make the tutorial manageable, I've decided not to post the following configuration files in this tutorial:
web.xml
spring-servlet.xml
applicationContext.xml
These files are standard Spring MVC related configuration files. You can find them in the downloadable application at the end of this tutorial.

I have also left out the JSP declarations. You can find a description of them in the following tutorial: Spring MVC 3: Using a Document-Oriented Database - MongoDB

Run the Application
To run the application, open your browser and enter the following URL:
http://localhost:8080/spring-data-mongodb/krams/main/persons
You should see the following CRUD view:



Conclusion
That's it. We have successfully refactored our existing Spring MVC 3 - MongoDB application to use the newly released Spring Data Document 1.0 for MongoDB. We've compared side-by-side between the native MongoDB development and with the new Spring Data framework. We have seen how Spring Data has simplified our development further.

Download the project
You can access the project site at Google's Project Hosting at http://code.google.com/p/spring-mvc-mongodb/

You can download the project as a Maven build. Look for the spring-data-mongodb.zip in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
此处为备份 from:
http://krams915.blogspot.com/2011/02/spring-data-mongodb-tutorial.html(墙内无法访问)
For Jetty: mvn jetty:run

If you want to learn more about Spring MVC and integration with other technologies, feel free to read my other tutorials in the Tutorials section.


<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">
    
   <context:annotation-config/>
    <context:component-scan base-package="com" >
    	<context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    <!-- Default bean name is 'mongo' -->
   	<mongo:mongo host="192.168.0.124" id="mongo"/>
    <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
    	<constructor-arg name="mongo" ref="mongo"/>
    	<constructor-arg name="databaseName" value="test"/>
    </bean>
</beans>


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/applicationContext.xml")
public class AppTest {
	
	@Resource(name="mongoTemplate")
	private MongoTemplate mongoTemplate;
	
	@Test public void save() throws Exception{
		User user = new User("1005", "jackerx", "xff", 24);
		this.mongoTemplate.save(user);
	}
	
	@Test public void findOne() throws Exception{
		User user = this.mongoTemplate.findOne(new Query(Criteria.where("id").is("1001")),User.class);
		System.out.println("user : " + ToStringBuilder.reflectionToString(user));
		
	}

	@Test public void find() throws Exception{
		Query query = new Query();
		query.addCriteria(Criteria.where("id").gt("10"));
		query.fields().exclude("qq");
		query.sort().on("name", Order.ASCENDING);
		List<User> users = mongoTemplate.find(query, User.class);
		for (User user : users) {
			System.out.println(ToStringBuilder.reflectionToString(user));
		}
		
	}
	@Test public void findAll() throws Exception{
		List<User> users = mongoTemplate.findAll(User.class);
		for (User user : users) {
			System.out.println(ToStringBuilder.reflectionToString(user));
		}
		
	}
	@Test public void update() throws Exception{
		// 更新
		mongoTemplate.updateFirst(new Query(Criteria.where("firstname").is("yong")),
				Update.update("lastname", "new lastname"), "userprofile");
		User updatedUser = mongoTemplate.findOne(new Query(Criteria.where("id").is("1001")),User.class);
		System.out.println("updatedUser : " + updatedUser);
	}
	@Test public void delete() throws Exception{
		// 删除
		mongoTemplate.remove(new Query(Criteria.where("id").is("1001")),User.class);
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics