使用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
app-config.xml
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: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
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
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
// 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