Spring data MongoDB

原文地址  http://miller-cn.iteye.com/blog/1258859


在这个教程中,我们将对一个存在的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 

Java代码   收藏代码
  1. package org.krams.tutorial.domain;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. /** 
  6.  * A simple POJO representing a Person 
  7.  * 一个简单的POJO 
  8.  * @author Krams  
  9.  */  
  10. public class Person implements Serializable {  
  11.   
  12.  private static final long serialVersionUID = -5527566248002296042L;  
  13.    
  14.  private String pid;  
  15.  private String firstName;  
  16.  private String lastName;  
  17.  private Double money;  
  18.   
  19.  public String getPid() {  
  20.   return pid;  
  21.  }  
  22.   
  23.  public void setPid(String pid) {  
  24.   this.pid = pid;  
  25.  }  
  26.   
  27.  public String getFirstName() {  
  28.   return firstName;  
  29.  }  
  30.   
  31.  public void setFirstName(String firstName) {  
  32.   this.firstName = firstName;  
  33.  }  
  34.   
  35.  public String getLastName() {  
  36.   return lastName;  
  37.  }  
  38.   
  39.  public void setLastName(String lastName) {  
  40.   this.lastName = lastName;  
  41.  }  
  42.   
  43.  public Double getMoney() {  
  44.   return money;  
  45.  }  
  46.   
  47.  public void setMoney(Double money) {  
  48.   this.money = money;  
  49.  }  
  50. }  


注意: 
我们通常使用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 

Java代码   收藏代码
  1. package org.krams.tutorial.service;  
  2.   
  3. import java.util.List;  
  4. import java.util.UUID;  
  5.   
  6. import javax.annotation.Resource;  
  7. import org.apache.log4j.Logger;  
  8. import org.krams.tutorial.domain.Person;  
  9. import org.springframework.data.document.mongodb.MongoTemplate;  
  10. import org.springframework.data.document.mongodb.query.Query;  
  11. import org.springframework.data.document.mongodb.query.Update;  
  12. import org.springframework.stereotype.Service;  
  13. import org.springframework.transaction.annotation.Transactional;  
  14. import static org.springframework.data.document.mongodb.query.Criteria.where;  
  15.   
  16. /** 
  17.  * Service for processing {@link Person} objects. 
  18.  * Uses Spring's {@link MongoTemplate} to perform CRUD operations. 
  19.  *  
  20.  * For a complete reference to MongoDB 
  21.  * see http://www.mongodb.org/ 
  22.  *  
  23.  * For a complete reference to Spring Data MongoDB  
  24.  * see http://www.springsource.org/spring-data 
  25.  *  
  26.  * @author Krams at {@link http://krams915@blogspot.com} 
  27.  */  
  28. @Service(personService)  
  29. @Transactional  
  30. public class PersonService {  
  31.   
  32.  protected static Logger logger = Logger.getLogger(service);  
  33.    
  34.  @Resource(name=mongoTemplate)  
  35.  private MongoTemplate mongoTemplate;  
  36.    
  37.  /** 
  38.   * 获取所有的 person 
  39.   */  
  40.  public List getAll() {  
  41.   logger.debug(Retrieving all persons);  
  42.    
  43.   // 查找一个属性(pid)存在的条目  
  44.         Query query = new Query(where(pid).exists(true));  
  45.         
  46.         //执行查询,查找所有的存在的Person条目  
  47.         List persons = mongoTemplate.find(query, Person.class);  
  48.           
  49.   return persons;  
  50.  }  
  51.    
  52.  /** 
  53.   * 获取一个 person 
  54.   */  
  55.  public Person get( String id ) {  
  56.   logger.debug(Retrieving an existing person);  
  57.     
  58.   // 获取一个pid匹配id的条目  
  59.         Query query = new Query(where(pid).is(id));  
  60.         // 执行查询,并找到一个匹配的条目   
  61.         Person person = mongoTemplate.findOne(mycollection, query, Person.class);  
  62.        
  63.   return person;  
  64.  }  
  65.    
  66.  /** 
  67.   * 添加一个新的person 
  68.   */  
  69.  public Boolean add(Person person) {  
  70.   logger.debug(Adding a new user);  
  71.     
  72.   try {  
  73.      
  74.    //设置一个新值的PID(UUID)  
  75.    person.setPid(UUID.randomUUID().toString());  
  76.    // 插入到DB  
  77.       mongoTemplate.insert(mycollection, person);  
  78.   
  79.    return true;  
  80.      
  81.   } catch (Exception e) {  
  82.    logger.error(An error has occurred while trying to add new user,e);  
  83.    return false;  
  84.   }  
  85.  }  
  86.    
  87.  /** 
  88.   * 删除一个存在的person 
  89.   */  
  90.  public Boolean delete(String id) {  
  91.   logger.debug(Deleting existing person);  
  92.     
  93.   try {  
  94.      
  95.         // 获取一个pid匹配id的条目  
  96.          Query query = new Query(where(pid).is(id));  
  97.          // 运行查询和删除条目    
  98.          mongoTemplate.remove(query);  
  99.            
  100.    return true;  
  101.      
  102.   } catch (Exception e) {  
  103.    logger.error(An error has occurred while trying to delete new user, e);  
  104.    return false;  
  105.   }  
  106.  }  
  107.    
  108.  /** 
  109.   *编辑一个存在的Persn 
  110.   */  
  111.  public Boolean edit(Person person) {  
  112.   logger.debug(Editing existing person);  
  113.     
  114.   try {  
  115.      
  116.    // 获取一个pid匹配id的条目  
  117.          Query query = new Query(where(pid).is(person.getPid()));  
  118.            
  119.    // 声明一个更新的对象。  
  120.          // 此相匹配的更新修饰符在MongoDBThis matches the update modifiers available in MongoDB  
  121.        Update update = new Update();  
  122.            
  123.          update.set(firstName, person.getFirstName());  
  124.          mongoTemplate.updateMulti(query, update);  
  125.            
  126.          update.set(lastName, person.getLastName());  
  127.          mongoTemplate.updateMulti(query, update);  
  128.            
  129.          update.set(money, person.getMoney());  
  130.          mongoTemplate.updateMulti(query, update);  
  131.            
  132.    return true;  
  133.      
  134.   } catch (Exception e) {  
  135.    logger.error(An error has occurred while trying to edit existing user, e);  
  136.    return false;  
  137.   }  
  138.     
  139.  }  
  140. }  


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

Java代码   收藏代码
  1. public List getAll() {  
  2.   logger.debug(Retrieving all persons);  
  3.      
  4.   // 获取到集合  
  5.   DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);  
  6.   // 为了遍历数据记录获取到游标   
  7.      DBCursor cur = coll.find();  
  8.      // 创建一个新的List  
  9.   List items = new ArrayList();  
  10.   // 遍历游标  
  11.         while(cur.hasNext()) {  
  12.          // 建立从 DBOject 到 Person的关系  
  13.          DBObject dbObject = cur.next();  
  14.          Person person = new Person();  
  15.             
  16.          person.setId(dbObject.get(id).toString());  
  17.          person.setFirstName(dbObject.get(firstName).toString());  
  18.          person.setLastName(dbObject.get(lastName).toString());  
  19.          person.setMoney(Double.valueOf(dbObject.get(money).toString()));  
  20.    
  21.          // 添加到新的List  
  22.          items.add(person);  
  23.         }  
  24.            
  25.         // Return list  
  26.   return items;  
  27.  }  

通过Spring Data的实现 

Java代码   收藏代码
  1. public List getAll() {  
  2.   logger.debug(Retrieving all persons);  
  3.    
  4.         Query query = new Query(where(pid).exists(true));  
  5.         List persons = mongoTemplate.find(query, Person.class);  
  6.           
  7.   return persons;  
  8.  }  

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

Java代码   收藏代码
  1. public Person get( String id ) {  
  2.   logger.debug(Retrieving an existing person);  
  3.      
  4.   // 获取集合  
  5.   DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);  
  6.   // 创建一个新的对象  
  7.   DBObject doc = new BasicDBObject();  
  8.   //用ID来搜索  
  9.         doc.put(id, id);  
  10.            
  11.         // 查找,并返回给定ID对应的人  
  12.         DBObject dbObject = coll.findOne(doc);  
  13.            
  14.         // 建立从 DBOject 到 Person的关系  
  15.      Person person = new Person();  
  16.      person.setId(dbObject.get(id).toString());  
  17.      person.setFirstName(dbObject.get(firstName).toString());  
  18.      person.setLastName(dbObject.get(lastName).toString());  
  19.      person.setMoney(Double.valueOf(dbObject.get(money).toString()));  
  20.         
  21.         // Return person  
  22.   return person;  
  23.  }  

通过Spring Data的实现 

Java代码   收藏代码
  1. public Person get( String id ) {  
  2.   logger.debug(Retrieving an existing person);  
  3.     
  4.   // 查找一个条目,其中PID相匹配的ID  
  5.         Query query = new Query(where(pid).is(id));  
  6.         // 执行查询,并找到一个匹配的条目  
  7.         Person person = mongoTemplate.findOne(mycollection, query, Person.class);  
  8.        
  9.   return person;  
  10.  }  


添加一个Person 
传统的MongoDB实现 

Java代码   收藏代码
  1. public Boolean add(Person person) {  
  2.   logger.debug(Adding a new user);  
  3.      
  4.   try {  
  5.    // 获取集合  
  6.    DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);  
  7.    // 创建一个Object  
  8.    BasicDBObject doc = new BasicDBObject();  
  9.    //使用UUID 随机生成的ID  
  10.    // See http://en.wikipedia.org/wiki/Universally_unique_identifier  
  11.          doc.put(id, UUID.randomUUID().toString() );   
  12.          doc.put(firstName, person.getFirstName());  
  13.          doc.put(lastName, person.getLastName());  
  14.          doc.put(money, person.getMoney());  
  15.          //  保存  
  16.          coll.insert(doc);  
  17.             
  18.    return true;  
  19.       
  20.   } catch (Exception e) {  
  21.    logger.error(An error has occurred while trying to add new user, e);  
  22.    return false;  
  23.   }  
  24.  }  


通过Spring Data的实现 

Java代码   收藏代码
  1. public Boolean add(Person person) {  
  2.   logger.debug(Adding a new user);  
  3.     
  4.   try {  
  5.      
  6.    // 设置一个新值的PID(UUID)  
  7.    person.setPid(UUID.randomUUID().toString());  
  8.    // 保存到DB  
  9.       mongoTemplate.insert(mycollection, person);  
  10.   
  11.    return true;  
  12.      
  13.   } catch (Exception e) {  
  14.    logger.error(An error has occurred while trying to add new user, e);  
  15.    return false;  
  16.   }  
  17.  }  

删除一个条目 
传统的MongoDB实现 
Java代码   收藏代码
  1. public Boolean delete(String id) {  
  2.   logger.debug(Deleting existing person);  
  3.      
  4.   try {  
  5.    // 检索一个条目  
  6.    BasicDBObject item = (BasicDBObject) getDBObject( id );  
  7.    // 获取集合  
  8.    DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);  
  9.    // 删除检索到的条目  
  10.          coll.remove(item);  
  11.             
  12.    return true;  
  13.       
  14.   } catch (Exception e) {  
  15.    logger.error(An error has occurred while trying to delete new user, e);  
  16.    return false;  
  17.   }  
  18.  }  
通过Spring Data的实现 
Java代码   收藏代码
  1. public Boolean delete(String id) {  
  2.   logger.debug(Deleting existing person);  
  3.     
  4.   try {  
  5.      
  6.    // 通过id检索到一个Person  
  7.          Query query = new Query(where(pid).is(id));  
  8.          // 运行查询和删除  
  9.          mongoTemplate.remove(query);  
  10.            
  11.    return true;  
  12.      
  13.   } catch (Exception e) {  
  14.    logger.error(An error has occurred while trying to delete new user, e);  
  15.    return false;  
  16.   }  
  17.  }  



更新一个条目 
传统的MongoDB实现 
Java代码   收藏代码
  1. public Boolean edit(Person person) {  
  2.   logger.debug(Editing existing person);  
  3.      
  4.   try {  
  5.    // 检索一个条目  
  6.    BasicDBObject existing = (BasicDBObject) getDBObject( person.getId() );  
  7.       
  8.    DBCollection coll = MongoDBFactory.getCollection(mydb,mycollection);  
  9.       
  10.    // 创建一个新的对象  
  11.    BasicDBObject edited = new BasicDBObject();  
  12.    // 分配现有的属性  
  13.    edited.put(id, person.getId());   
  14.    edited.put(firstName, person.getFirstName());  
  15.    edited.put(lastName, person.getLastName());  
  16.    edited.put(money, person.getMoney());  
  17.    // 更新  
  18.          coll.update(existing, edited);  
  19.             
  20.    return true;  
  21.       
  22.   } catch (Exception e) {  
  23.    logger.error(An error has occurred while trying to edit existing user, e);  
  24.    return false;  
  25.   }  
  26.      
  27.  }  
  28.   
  29.  //通过Spring Data的实现  
  30. public Boolean edit(Person person) {  
  31.   logger.debug(Editing existing person);  
  32.     
  33.   try {  
  34.      
  35.    // 通过id查询数据  
  36.          Query query = new Query(where(pid).is(person.getPid()));  
  37.            
  38.    // 声明一个更新对象  
  39.          // 此相匹配的更新修饰符在MongoDB 。This matches the update modifiers available in MongoDB  
  40.    Update update = new Update();  
  41.            
  42.          update.set(firstName, person.getFirstName());  
  43.          mongoTemplate.updateMulti(query, update);  
  44.            
  45.          update.set(lastName, person.getLastName());  
  46.          mongoTemplate.updateMulti(query, update);  
  47.            
  48.          update.set(money, person.getMoney());  
  49.          mongoTemplate.updateMulti(query, update);  
  50.            
  51.    return true;  
  52.      
  53.   } catch (Exception e) {  
  54.    logger.error(An error has occurred while trying to edit existing user, e);  
  55.    return false;  
  56.   }  
  57.     
  58.  }  


配置 
利用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 

Java代码   收藏代码
  1. package org.krams.tutorial.service;  
  2.   
  3. import java.util.UUID;  
  4.   
  5. import javax.annotation.Resource;  
  6. import org.apache.log4j.Logger;  
  7. import org.krams.tutorial.domain.Person;  
  8. import org.springframework.data.document.mongodb.MongoTemplate;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10.   
  11. /** 
  12.  * MongoDB的例子数据初始化 Service  
  13.  *  
  14.  * 一个完整的应用 MongoDB 
  15.  *  http://www.mongodb.org/ 
  16.  *  
  17.  *  http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html 
  18.  *  
  19.  * @author Krams at {@link http://krams915@blogspot.com} 
  20.  */  
  21. @Transactional  
  22. public class InitService {  
  23.   
  24.  protected static Logger logger = Logger.getLogger(service);  
  25.    
  26.  @Resource(name=mongoTemplate)  
  27.  private MongoTemplate mongoTemplate;  
  28.   
  29.  private void init() {  
  30.   // 填充我们的MongoDB数据库  
  31.   logger.debug(Init MongoDB users);  
  32.     
  33.   // Drop 存在的 collection  
  34.   mongoTemplate.dropCollection(mycollection);  
  35.     
  36.   // 创建一个新的对象  
  37.   Person p = new Person ();  
  38.   p.setPid(UUID.randomUUID().toString());  
  39.   p.setFirstName(John);  
  40.   p.setLastName(Smith);  
  41.   p.setMoney(1000.0);  
  42.     
  43.   // 插入到DB  
  44.      mongoTemplate.insert(mycollection, p);  
  45.   
  46.      // 创建一个新的对象  
  47.   p = new Person ();  
  48.   p.setPid(UUID.randomUUID().toString());  
  49.   p.setFirstName(Jane);  
  50.   p.setLastName(Adams);  
  51.   p.setMoney(2000.0);  
  52.     
  53.   // 插入到db  
  54.      mongoTemplate.insert(mycollection, p);  
  55.           
  56.      // 创建一个新的对象  
  57.   p = new Person ();  
  58.   p.setPid(UUID.randomUUID().toString());  
  59.   p.setFirstName(Jeff);  
  60.   p.setLastName(Mayer);  
  61.   p.setMoney(3000.0);  
  62.     
  63.   // 插入到  
  64.      mongoTemplate.insert(mycollection, p);  
  65.  }  
  66. }  

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

MainController.java 
Java代码   收藏代码
  1. package org.krams.tutorial.controller;  
  2.   
  3. import java.util.List;  
  4. import javax.annotation.Resource;  
  5. import org.apache.log4j.Logger;  
  6. import org.krams.tutorial.domain.Person;  
  7. import org.krams.tutorial.service.PersonService;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.ui.Model;  
  10. import org.springframework.web.bind.annotation.ModelAttribute;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.RequestParam;  
  14.   
  15.   
  16. /** 
  17.  * 处理和检索人的请求  
  18.  *  
  19.  * @author Krams at {@link http://krams915@blogspot.com} 
  20.  */  
  21. @Controller  
  22. @RequestMapping(/main)  
  23. public class MainController {  
  24.   
  25.  protected static Logger logger = Logger.getLogger(controller);  
  26.    
  27.  @Resource(name=personService)  
  28.  private PersonService personService;  
  29.    
  30.  /** 
  31.   * 处理和检索所有的All Person,并显示在JSP页面中  
  32.   *  
  33.   * @return the name of the JSP page 
  34.   */  
  35.     @RequestMapping(value = /persons, method = RequestMethod.GET)  
  36.     public String getPersons(Model model) {  
  37.        
  38.      logger.debug(Received request to show all persons);  
  39.        
  40.      // 获得所有的人,把调用委托给PersonService  
  41.      List persons = personService.getAll();  
  42.        
  43.      // Attach persons to the Model  
  44.      model.addAttribute(persons, persons);  
  45.        
  46.      // This will resolve to /WEB-INF/jsp/personspage.jsp  
  47.      return personspage;  
  48.  }  
  49.       
  50.     /** 
  51.      * 检索,添加页面 
  52.      *  
  53.      * @return the name of the JSP page 
  54.      */  
  55.     @RequestMapping(value = /persons/add, method = RequestMethod.GET)  
  56.     public String getAdd(Model model) {  
  57.      logger.debug(Received request to show add page);  
  58.       
  59.      // 创建新的Person,并添加到模型   
  60.      // This is the formBackingOBject  
  61.      model.addAttribute(personAttribute, new Person());  
  62.   
  63.      // This will resolve to /WEB-INF/jsp/addpage.jsp  
  64.      return addpage;  
  65.  }  
  66.    
  67.     /** 
  68.      * 增加了一个新的Person,通过委托加工PersonService。  
  69.      *显示一个确认JSP页面 
  70.      * @return  the name of the JSP page 
  71.      */  
  72.     @RequestMapping(value = /persons/add, method = RequestMethod.POST)  
  73.     public String add(@ModelAttribute(personAttribute) Person person) {  
  74.   logger.debug(Received request to add new person);  
  75.     
  76.      // The personAttribute model has been passed to the controller from the JSP  
  77.      // We use the name personAttribute because the JSP uses that name  
  78.     
  79.   // Call PersonService to do the actual adding  
  80.   personService.add(person);  
  81.   
  82.      // This will resolve to /WEB-INF/jsp/addedpage.jsp  
  83.   return addedpage;  
  84.  }  
  85.       
  86.     /** 
  87.      * Deletes an existing person by delegating the processing to PersonService. 
  88.      * Displays a confirmation JSP page 
  89.      *  
  90.      * @return  the name of the JSP page 
  91.      */  
  92.     @RequestMapping(value = /persons/delete, method = RequestMethod.GET)  
  93.     public String delete(@RequestParam(value=pid, required=true) String id,   
  94.               Model model) {  
  95.      
  96.   logger.debug(Received request to delete existing person);  
  97.     
  98.   // Call PersonService to do the actual deleting  
  99.   personService.delete(id);  
  100.     
  101.   // Add id reference to Model  
  102.   model.addAttribute(pid, id);  
  103.        
  104.      // This will resolve to /WEB-INF/jsp/deletedpage.jsp  
  105.   return deletedpage;  
  106.  }  
  107.       
  108.     /** 
  109.      * Retrieves the edit page 
  110.      *  
  111.      * @return the name of the JSP page 
  112.      */  
  113.     @RequestMapping(value = /persons/edit, method = RequestMethod.GET)  
  114.     public String getEdit(@RequestParam(value=pid, required=true) String id,    
  115.               Model model) {  
  116.      logger.debug(Received request to show edit page);  
  117.       
  118.      // Retrieve existing Person and add to model  
  119.      // This is the formBackingOBject  
  120.      model.addAttribute(personAttribute, personService.get(id));  
  121.        
  122.      // This will resolve to /WEB-INF/jsp/editpage.jsp  
  123.      return editpage;  
  124.  }  
  125.       
  126.     /** 
  127.      * Edits an existing person by delegating the processing to PersonService. 
  128.      * Displays a confirmation JSP page 
  129.      *  
  130.      * @return  the name of the JSP page 
  131.      */  
  132.     @RequestMapping(value = /persons/edit, method = RequestMethod.POST)  
  133.     public String saveEdit(@ModelAttribute(personAttribute) Person person,   
  134.                  @RequestParam(value=pid, required=true) String id,   
  135.                 Model model) {  
  136.      logger.debug(Received request to update person);  
  137.       
  138.      // The personAttribute model has been passed to the controller from the JSP  
  139.      // We use the name personAttribute because the JSP uses that name  
  140.        
  141.      // We manually assign the id because we disabled it in the JSP page  
  142.      // When a field is disabled it will not be included in the ModelAttribute  
  143.      person.setPid(id);  
  144.        
  145.      // Delegate to PersonService for editing  
  146.      personService.edit(person);  
  147.        
  148.      // Add id reference to Model  
  149.   model.addAttribute(pid, id);  
  150.     
  151.      // This will resolve to /WEB-INF/jsp/editedpage.jsp  
  152.   return editedpage;  
  153.  }  
  154.       
  155. }  
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. 


Java代码   收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:mongo="http://www.springframework.org/schema/data/mongo"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/context  
  6.           http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  7.           http://www.springframework.org/schema/data/mongo  
  8.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd  
  9.           http://www.springframework.org/schema/beans  
  10.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  11.       
  12.    <context:annotation-config/>  
  13.     <context:component-scan base-package="com" >  
  14.         <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>  
  15.     </context:component-scan>  
  16.     <!-- Default bean name is 'mongo' -->  
  17.     <mongo:mongo host="192.168.0.124" id="mongo"/>  
  18.     <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">  
  19.         <constructor-arg name="mongo" ref="mongo"/>  
  20.         <constructor-arg name="databaseName" value="test"/>  
  21.     </bean>  
  22. </beans>  
  23.   
  24.   
  25. @RunWith(SpringJUnit4ClassRunner.class)  
  26. @ContextConfiguration(locations="/applicationContext.xml")  
  27. public class AppTest {  
  28.       
  29.     @Resource(name="mongoTemplate")  
  30.     private MongoTemplate mongoTemplate;  
  31.       
  32.     @Test public void save() throws Exception{  
  33.         User user = new User("1005""jackerx""xff"24);  
  34.         this.mongoTemplate.save(user);  
  35.     }  
  36.       
  37.     @Test public void findOne() throws Exception{  
  38.         User user = this.mongoTemplate.findOne(new Query(Criteria.where("id").is("1001")),User.class);  
  39.         System.out.println("user : " + ToStringBuilder.reflectionToString(user));  
  40.           
  41.     }  
  42.   
  43.     @Test public void find() throws Exception{  
  44.         Query query = new Query();  
  45.         query.addCriteria(Criteria.where("id").gt("10"));  
  46.         query.fields().exclude("qq");  
  47.         query.sort().on("name", Order.ASCENDING);  
  48.         List<User> users = mongoTemplate.find(query, User.class);  
  49.         for (User user : users) {  
  50.             System.out.println(ToStringBuilder.reflectionToString(user));  
  51.         }  
  52.           
  53.     }  
  54.     @Test public void findAll() throws Exception{  
  55.         List<User> users = mongoTemplate.findAll(User.class);  
  56.         for (User user : users) {  
  57.             System.out.println(ToStringBuilder.reflectionToString(user));  
  58.         }  
  59.           
  60.     }  
  61.     @Test public void update() throws Exception{  
  62.         // 更新  
  63.         mongoTemplate.updateFirst(new Query(Criteria.where("firstname").is("yong")),  
  64.                 Update.update("lastname""new lastname"), "userprofile");  
  65.         User updatedUser = mongoTemplate.findOne(new Query(Criteria.where("id").is("1001")),User.class);  
  66.         System.out.println("updatedUser : " + updatedUser);  
  67.     }  
  68.     @Test public void delete() throws Exception{  
  69.         // 删除  
  70.         mongoTemplate.remove(new Query(Criteria.where("id").is("1001")),User.class);  
  71.     }  
  72.   
  73. }  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值