spring整合mongodb 1

来源:互联网 发布:网络主播 日语 编辑:程序博客网 时间:2024/05/18 04:16

转载自:http://my.oschina.net/u/1013711/blog/207987

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代码  收藏代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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>
    注意:url-pattern的配置为‘/’。  

    (2)配置applicationContext.xml  

Java代码  收藏代码

  1. ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <?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.0this tag works in Servlet MVC only!  -->  
        <mvc:annotation-driven />   
           
        <!-- Loads MongoDB configuraton -->  
        <import resource="mongo-config.xml"/>   
                   
    </beans>



(3)配置mongo-config.xml 

Java代码  收藏代码

  1. ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?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 

Java代码  收藏代码

  1. ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?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层 

Java代码  收藏代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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);  
           
    }  
       
}

Java代码  收藏代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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+"}}";  
    }  
       
}
    http://localhost:8080/TestSpringMongodb/user/save?name=xiaohong&age=23  
    save:{USER:{uid:5020bef0fe7d16eb86275c7a,name:xiaohong,age:23}}  
    http://localhost:8080/TestSpringMongodb/user/find?name=xiaohong  
    find:{USER:{uid:5020bef0fe7d16eb86275c7a,name:xiaohong,age:23}}  
0 0
原创粉丝点击