Spring Mongodb
目錄
1 SPRING整合MONGODB 1
1.1 環境準備 1
1.2 包依賴 1
1.3 配置 2
2 案列 5
2.1 SPRING MVC整合MONGODB代碼案例 5
1 Spring整合Mongodb
1.1 環境準備
1. mongodb官網 http://www.mongodb.org/,下載mongodb安裝包和mongodb的java驅動包。
mongodb安裝包(下載地址http://www.mongodb.org/downloads)。Mongodb的安裝和使用可見mongodb權威指南。
mongodb驅動包(下載地址https://github.com/mongodb/mongo-java-driver/downloads)
2. Spring下載中心(http://www.springsource.org/download/community)下載spring,spring-data-mongodb,spring-data-commons包。
1.2 包依賴
項目所需依賴包以下:
Mongodb驅動包:
mongo-2.8.0.jar
spring包:
aopalliance-1.0.jar
commons-logging-1.1.jar
org.springframework.aop-3.1.RELEASE.jar
org.springframework.asm-3.1.RELEASE.jar
org.springframework.beans-3.1.RELEASE.jar
org.springframework.context-3.1.RELEASE.jar
org.springframework.context.support-3.1.RELEASE.jar
org.springframework.core-3.1.RELEASE.jar
org.springframework.expression-3.1.RELEASE.jar
org.springframework.transaction-3.1.RELEASE.jar
org.springframework.web-3.1.RELEASE.jar
org.springframework.web.servlet-3.1.RELEASE.jar
log4j-1.2.16.jar
slf4j-log4j12-1.6.4.jar
slf4j-api-1.6.4.jar
Spring Data Mongodb包:
spring-data-mongodb-1.1.0.M2.jar
Spring Data Commons包:
spring-data-commons-core-1.4.0.M1.jar
1.3 配置
(1)配置Web.xml
java
<?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>TestSpringMongodb</display-name> <!— spring mvc dispatcher servlet --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 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"> <!-- Activates various annotations to be detected in bean classes --> <context:annotation-config /> <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.For example @Controller and @Service . Make sure to set the correct base-package--> <context:component-scan base-package="bgi.contrl" /> <context:component-scan base-package="bgi.service" /> <!-- Configures the annotation-driven Spring MVC Controller programming model.Note that, with Spring 3.0, this tag works in Servlet MVC only! --> <mvc:annotation-driven /> <!-- Loads MongoDB configuraton --> <import resource="mongo-config.xml"/> </beans>
(3)配置mongo-config.xml
web
<?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:p="http://www.springframework.org/schema/p" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"> <!-- Default bean name is 'mongo' --> <mongo:mongo host="localhost" port="27017"/> <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="test"/> </bean> </beans>
注意:官方文檔和案例配置都是舊版本的配置案例,spring-data-mongo從1.0.0.M1到1.0.0.M3的版本叫作Spring Data Document。1.0.0.M4開始改名爲Spring Data MongoDB 1.0.0 M4,不過官網並無特別說明,乍一看有點莫名其妙,尤爲是MongoTemplate從org.springframework.data.document.mongod移動到org.springframework.data.mongodb.core,官網的HelloWorldExample卻仍是用org.springframework.data.document.mongodb作配置案例。多少會致使使用時的誤導。
(4)配置spring-servlet.xml
mongodb
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Declare a view resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> </beans>
注意:spring-servlet.xml的命名是根據web.xml中配置spring DispatcherServlet的名字 (<servlet-name>spring</servlet-name>)加上-servlet命名的。
2 案列
2.1 Spring mvc整合mongodb代碼案例
(1),control層
api
package bgi.contrl; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import bgi.pojo.User; import bgi.service.UserService; @Controller @RequestMapping("/user") public class UserCtrl { private static Logger logger = Logger.getLogger(UserCtrl.class.getName()); @Autowired UserService userService; @RequestMapping("/index") public ModelAndView index(){ ModelAndView mav = new ModelAndView("/user/index"); return mav; } @RequestMapping("/save") public ModelAndView saveUser(User user){ ModelAndView mav = new ModelAndView("/user/index"); logger.info("save:"+user); userService.saveUser(user); return mav; } @RequestMapping("/find") public ModelAndView findUser(User user){ ModelAndView mav = new ModelAndView("/user/index"); user = userService.findUserByName(user.getName()); logger.info("find:"+user); return mav; } } (2),service層 Java代碼 package bgi.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import bgi.pojo.User; @Service public class UserService { private static String USER_COLLECTION = "user"; @Autowired MongoTemplate mongoTemplate; /** * * @param user */ public void saveUser(User user){ mongoTemplate.save(user, USER_COLLECTION); } /** * * @param name * @return */ public User findUserByName(String name){ return mongoTemplate.findOne(new Query(Criteria.where("name").is(name)), User.class, USER_COLLECTION); } }
package bgi.pojo; import java.io.Serializable; import org.springframework.data.annotation.Id; public class User implements Serializable{ private static final long serialVersionUID = 1L; @Id String uid; String name; int age; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "{USER:{uid:"+this.uid+",name:"+this.name+",age:"+this.age+"}}"; } }