D:\mongodb\bin>mongod.exe --dbpath=d:\mongodata\data0 --port=10001 --replSet rcw /127.0.0.1:20001 D:\mongodb\bin>mongod.exe --dbpath=d:\mongodata\data1 --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:\mongodb\bin>mongod.exe --dbpath=d:\mongodata\data1 --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
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>人才信息管理</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/config/spring/app-config.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/config/spring/mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- <filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/commons/timeout.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/commons/timeout.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/WEB-INF/views/commons/timeout.jsp</location> </error-page> </web-app>
app-config.xml
<?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: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:property-placeholder location="classpath:/config/db.properties" /> <!-- Activate Spring Data MongoDB repository support --> <mongo:repositories base-package="com.fox.mongo" /> <!-- Add Replica Set support --> <mongo:mongo id="mongo" replica-set="${mongo.replica.set}"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg value="${mongo.db.name}"/> <!-- <constructor-arg value="example"/> --> </bean> <!-- Service for initializing MongoDB with sample data using MongoTemplate --> <bean id="initMongoService" class="com.fox.service.InitService" init-method="init"/> <!-- To translate any MongoExceptions thrown in @Repository annotated classes --> <context:component-scan base-package="com.fox"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:annotation-config /> </beans>
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
<?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: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"> <!-- 只搜索@Controller 标注的类 不搜索其他标注的类 --> <context:component-scan base-package="com.fox.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:annotation-config /> <!-- 对某些静态资源,如css,图片等进行过滤 ,有引用 "/resources/**" 的路径引用转到工程的/resources/目录取资源 --> <!-- <mvc:resources mapping="/favicon.ico" location="/favicon.ico"/> --> <mvc:resources location="/resources/" mapping="/resources/**" /> <!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <!-- Declare a view resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"/> </bean> </beans>
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://[email protected]} */ @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. * <p> * For a complete reference to MongoDB * see http://www.mongodb.org/ * <p> * For a complete reference to Spring Data MongoDB * see http://www.springsource.org/spring-data * * @author Krams at {@link http://[email protected]} */ @Service("personService") @Transactional public class PersonService { protected static Log logger = LogFactory.getLog("service"); @Resource(name="mongoTemplate") private MongoTemplate mongoTemplate; /** * Retrieves all persons */ public List<Person> 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<Person> 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://[email protected]} */ @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<Person> 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"; } }