`
zjnbshifox
  • 浏览: 316035 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

学习使用spring data连接mongodb replset

阅读更多
1、分别在两个命令窗口中以replset方式启动两个mongodb进程
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://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.
 * <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://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<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://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<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";
	}
    
}

分享到:
评论

相关推荐

    Spring Data MongoDB API(Spring Data MongoDB 开发文档).CHM

    Spring Data MongoDB API。 Spring Data MongoDB 开发文档。

    Spring-Data-MongoDB3.2

    为了提高性能,可以通过以下策略优化Spring Data MongoDB的使用: - 合理设计数据模型,利用MongoDB的文档结构优势。 - 使用索引来加速查询,但需注意过多的索引会增加写操作的开销。 - 调整MongoDB的配置参数,如...

    Spring Data MongoDB中文文档

    - **Spring Data MongoDB** 支持 MongoDB 的聚合框架,可以使用 `Aggregation` 和 `AggregationOperation` 来构建复杂的聚合管道。 - 聚合框架支持多种操作,包括但不限于 `$match`, `$group`, `$sort`, `$project` ...

    spring-data使用mongodbTemplate对MongoDB进行读写操作

    这个库是Spring Data框架的一部分,旨在简化数据访问层的实现,尤其在使用NoSQL数据库如MongoDB时。MongoDBTemplate是Spring Data MongoDB的核心组件,它提供了丰富的API来执行常见的数据库操作。 首先,让我们深入...

    spring mvc+spring data+mongodb实例1

    这个实例涵盖了Spring MVC的控制器设计、Spring Data MongoDB的使用,以及MongoDB的基础操作,是学习现代Java Web开发的一个好例子。通过阅读源码并动手实践,开发者可以加深对这三个技术的理解,并提升自己的技能。

    MongoDB初探(二)----使用spring-data配置mongodb

    在本篇“MongoDB初探(二)----使用spring-data配置mongodb”中,我们将深入探讨如何利用Spring Data框架来集成和操作MongoDB数据库。Spring Data是Spring生态系统的一个重要组成部分,它提供了与各种数据存储系统...

    springdata mongodb api文档

    当需要扩展SpringData的功能时,SpringData MongoDB也提供了一定的扩展机制,例如使用Query DSL扩展进行复杂查询,或者使用Web支持来构建基于SpringData MongoDB的Web应用。 对于那些希望了解如何使用SpringData ...

    spring-data-mongodb-1.8.0.RELEASE(含源码)

    - **MongoEntity**:Spring Data MongoDB 使用注解来定义对象如何映射到 MongoDB 文档。例如,`@Document` 注解标识一个类为 MongoDB 的文档实体,`@Id` 用于指定主键字段。 - **Field 映射**:`@Field` 注解用于...

    spring data mongodb代码参考

    配置Spring Data MongoDB主要包括设置MongoDB连接信息(如主机名、端口、数据库名等)和创建MongoDBTemplate或MongoRepository实例。在Spring Boot应用中,可以通过application.properties或yaml文件配置数据库连接...

    SpringMongodb参考文档.docx

    Spring Data MongoDB 2.1中的新特性 5.2。Spring Data MongoDB 2.0中的新特性 5.3。Spring Data MongoDB 1.10中的新特性 5.4。Spring Data MongoDB 1.9中的新特性 5.5。Spring Data MongoDB 1.8中的新特性 5.6。...

    spring-data-mongodb-1.2.0.RELEASE

    在 Spring 应用中使用 Spring Data MongoDB 需要配置 MongoDB 的连接信息,包括主机、端口、数据库名等。通过 @EnableMongoRepositories 注解启用 MongoDB 的仓储接口。 五、对象映射 Spring Data MongoDB 使用 @...

    spring-data-mongodb1.2.0

    6. **Spring Data REST**:当与Spring Data REST模块一起使用时,Spring Data MongoDB可以自动暴露Repository接口作为RESTful服务,便于Web服务的构建和消费。 7. **版本控制**:通过`@Version`注解,Spring Data ...

    Spring-data + MongoDb源码

    2. **实体映射**: 在Spring Data MongoDB中,我们使用`@Document`注解标记一个类作为MongoDB的文档对象。这个注解包含了数据库集合的名称。每个字段可以使用`@Id`注解来指定主键,或者让MongoDB自动生成。 3. **...

    Spring集成MongoDB官方指定jar包:spring-data-mongodb-1.4.1.RELEASE.jar

    Spring集成MongoDB官方指定jar包:spring-data-mongodb-1.4.1.RELEASE.jar

    spring-data-mongodb-parent-reference

    通过使用 Spring Data MongoDB,开发人员可以很容易地实现对 MongoDB 数据库的映射和操作,而无需编写大量的模板代码。这个框架支持快速开发且易于理解,它与 Spring 框架的其它部分能够很好地集成。 文档的标题为 ...

    Spring3+Spring-data-mongodb1.5.6示例

    在本示例中,我们将深入探讨如何在Spring 3框架中集成Spring Data MongoDB 1.5.6,以便高效地处理MongoDB数据库。...通过学习这些示例,你可以更好地理解和掌握Spring 3与Spring Data MongoDB 1.5.6的整合技巧。

    spring-data-mongodb api

    Spring Data MongoDB API 是一个强大的Java库,用于简化与MongoDB数据库的交互。它作为Spring Data项目的一部分,提供了统一的编程模型,使得开发人员能够轻松地利用MongoDB的强大功能。Spring Data MongoDB API允许...

    spring-data-mongodb.jar

    spring支持mongodb的jar包

    spring-data-mongodb-3.1.8.jar中文-英文对照文档.zip

    中文-英文对照文档,中英对照文档,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压 【***.jar中文文档.zip】,再解压其中的 【***-...

Global site tag (gtag.js) - Google Analytics