数据库

 首页 > 数据库 > MongoDB > 使用spring data连接MongoDB replset

使用spring data连接MongoDB replset

分享到:
【字体:
导读:
         摘要:1、分别在两个命令窗口中以replset方式启动两个mongodb进程D:\mongodb\binmongod.exe--dbpathd:\mongodata\data0--port10001--replSetrcw/127.0.0.1:20001D:\mongodb\binmongod.exe--dbpathd:\m...

使用spring data连接MongoDB replset
1、分别在两个命令窗口中以replset方式启动两个mongodb进程
D:mongodbbin>mongod.exe --dbpath=d:mongodatadata0 --port=10001 --replSet rcw
/127.0.0.1:20001
D:mongodbbin>mongod.exe --dbpath=d:mongodatadata1 --port=20001 --replSet rcw
/127.0.0.1:10001
2、连接到任何一个mongodb实例,初始话replset
mongo 127.0.0.1:10001/admin
> db.runCommand({"replSetInitiate":{
... "_id":"rcw",
... "members":[{
... "_id":1,
... "host":"127.0.0.1:10001"
... },
... {
... "_id":2,
... "host":"127.0.0.1:20001"
... }
... ]
... }})
3、再加入一个仲裁服务器
D:mongodbbin>mongod.exe --dbpath=d:mongodatadata1 --port 30001 replSet 127.0.0.1:10001
mongo 127.0.0.1:10001/admin
>rs.addArb({"127.0.0.1:30001"})

4、下载spring,spring-data-common即(spring-data-core)以及spring-mongodb,注意这里的data-common要下载1.2.1的,才能和mongodb1.0.1配合,最新版会出错,建立一个spring mvc项目,配置文件
web.xml



  人才信息管理
  
    contextConfigLocation
    classpath:/config/spring/app-config.xml
  

  
    org.springframework.web.context.ContextLoaderListener
  

  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:/config/spring/mvc-config.xml
    

    1
  

  
    SpringMVC
    /
  

  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    

    
      forceEncoding
      true
    

  

  
    encodingFilter
    /*
  

  
    org.springframework.web.context.request.RequestContextListener
  

  
    org.springframework.web.util.IntrospectorCleanupListener
  

  
  
    index.jsp
  

  
    500
    /WEB-INF/views/commons/timeout.jsp
  

  
    404
    /WEB-INF/views/commons/timeout.jsp
  

  
    403
    /WEB-INF/views/commons/timeout.jsp
  


app-config.xml


        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">
        
        
        
        
        
        
                
                
                
        
        
        
        
        
       
    
        

db.properties文件的内容

mongo.db.name=test
#mongo.host.name=localhost
#mongo.host.port=27017
mongo.replica.set=127.0.0.1:10001,127.0.0.1:20001
mvc-config.xml

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        
        
                
        
        
        
        
        
        
        
        
        
            
            
            
        

CRUD的代码都是复制过来稍微修改了一下,映射类的代码
package com.fox.mongo;
import java.io.Serializable;
import org.springframework.data.mongodb.core.mapping.Document;
/**
 * A simple POJO representing a Person
 *
 * @author Krams at {@link http://krams915@blogspot.com}
 */
@Document(collection="example")
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;
        }
}
service层的代码
package com.fox.service;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.WriteResultChecking;
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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fox.mongo.Person;
/**
 * 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 Log logger = LogFactory.getLog("service");
        @Resource(name="mongoTemplate")
        private MongoTemplate mongoTemplate;
        /**
         * Retrieves all persons
         */
        public List getAll() {
                logger.debug("Retrieving all persons");
                // Find an entry where pid property exists
        Query query = new Query(Criteria.where("pid").exists(true));
        // Execute the query and find all matching entries
        List persons = mongoTemplate.find(query, Person.class);
                return persons;
        }
        /**
         * Retrieves a single person
         */
        public Person get( String id ) {
                logger.debug("Retrieving an existing person");
                // Find an entry where pid matches the id
        Query query = new Query(Criteria.where("pid").is(id));
        // Execute the query and find one matching entry
        Person person = mongoTemplate.findOne(query, Person.class);
                return person;
        }
        /**
         * Adds a new person
         */
        public Boolean add(Person person) {
                logger.debug("Adding a new user");
                try {
                        // Set a new value to the pid property first since it's blank
                        person.setPid(UUID.randomUUID().toString());
                        // Insert to db
                    mongoTemplate.insert(person);
                        return true;
                } catch (Exception e) {
                        logger.error("An error has occurred while trying to add new user", e);
                        return false;
                }
        }
        /**
         * Deletes an existing person
         */
        public Boolean delete(String id) {
                logger.debug("Deleting existing person");
                try {
                        // Find an entry where pid matches the id
                Query query = new Query(Criteria.where("pid").is(id));
                // Run the query and delete the entry
                mongoTemplate.remove(query);
                        return true;
                } catch (Exception e) {
                        logger.error("An error has occurred while trying to delete new user", e);
                        return false;
                }
        }
        /**
         * Edits an existing person
         */
        public Boolean edit(Person person) {
                logger.debug("Editing existing person");
                try {
                        // Find an entry where pid matches the id
                Query query = new Query(Criteria.where("pid").is(person.getPid()));
                        // Declare an Update object.
                // This matches the update modifiers available in MongoDB
                        Update update = new Update();
                update.set("firstName", person.getFirstName());
                mongoTemplate.updateMulti(query, update, "example");
                update.set("lastName", person.getLastName());
                mongoTemplate.updateMulti(query, update,"example");
                update.set("money", person.getMoney());
                mongoTemplate.updateMulti(query, update,"example");
                        return true;
                } catch (Exception e) {
                        logger.error("An error has occurred while trying to edit existing user", e);
                        return false;
                }
        }
}
controller
package com.fox.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
import com.fox.mongo.Person;
import com.fox.service.PersonService;
/**
 * Handles and retrieves person request
 *
 * @author Krams at {@link http://krams915@blogspot.com}
 */
@Controller
@RequestMapping("/main")
public class MainController {
        protected static Log logger = LogFactory.getLog("controller");
        @Resource(name="personService")
        private PersonService personService;
        /**
         * Handles and retrieves all persons and show it in a JSP page
         *
         * @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");
        // Retrieve all persons by delegating the call to 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";
        }
    /**
     * Retrieves the add page
     *
     * @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");
        // Create new Person and add to model
        // This is the formBackingOBject
        model.addAttribute("personAttribute", new Person());
        // This will resolve to /WEB-INF/jsp/addpage.jsp
        return "addpage";
        }
    /**
     * Adds a new person by delegating the processing to PersonService.
     * Displays a confirmation JSP page
     *
     * @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";
        }
}
使用spring data连接MongoDB replset

分享到:
Ubuntu系统下使用python和MongoDB
Ubuntu系统下使用python和MongoDB mongodb install: sudo apt-get install mongodb Install pip 1. $ sudo apt-get install python-pip python-dev build-essential  $ sudo pip install --upgrade pip  $ sudo pip install --upgrade virtualenv  pip install pymongo (mysql:sudo pip instal...
在win7系统下安装配置MongoDB数据库
在win7系统下安装配置MongoDB数据库 又要学新东西了。 mongodb仅仅知道他是数据库,具体吗有待以后学习。 先说说怎么安装和配置吧。 官网地址:http://www.mongodb.org/display/DOCS/Home 里面的文档资料很多的,不懂得就看,我也是慢慢看的。 下载下来后(本人用的是win7 32位) 解压到一个固定地址中...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……