Spring MVC + Mongodb

在maven的pom.xml中增加引用:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.    <modelVersion>4.0.0</modelVersion>
  4.    <groupId>com.zjf</groupId>
  5.    <artifactId>springmvc</artifactId>
  6.    <version>0.0.1-SNAPSHOT</version>
  7.    <packaging>war</packaging>
  8.  
  9.    <properties>
  10.       <spring.webmvc.version>4.3.0.RELEASE</spring.webmvc.version>
  11.       <junit.version>4.8.2</junit.version>
  12.       <jedis.version>2.8.1</jedis.version>
  13.       <log4j.version>1.2.16</log4j.version>
  14.       <slf4j.version>1.7.2</slf4j.version>
  15.       <spring.data.redis.version>1.7.2.RELEASE</spring.data.redis.version>
  16.       <spring.data.mongodb.version>1.8.0.RELEASE</spring.data.mongodb.version>
  17.    </properties>
  18.  
  19.  
  20.    <dependencies>
  21.       <dependency>
  22.          <groupId>junit</groupId>
  23.          <artifactId>junit</artifactId>
  24.          <version>${junit.version}</version>
  25.          <scope>test</scope>
  26.       </dependency>
  27.       <dependency>
  28.          <groupId>org.springframework</groupId>
  29.          <artifactId>spring-webmvc</artifactId>
  30.          <version>${spring.webmvc.version}</version>
  31.       </dependency>
  32.       <dependency>
  33.          <groupId>redis.clients</groupId>
  34.          <artifactId>jedis</artifactId>
  35.          <version>${jedis.version}</version>
  36.       </dependency>
  37.       <dependency>
  38.          <groupId>org.springframework.data</groupId>
  39.          <artifactId>spring-data-redis</artifactId>
  40.          <version>${spring.data.redis.version}</version>
  41.       </dependency>
  42.       <dependency>
  43.          <groupId>org.springframework.data</groupId>
  44.          <artifactId>spring-data-mongodb</artifactId>
  45.          <version>${spring.data.mongodb.version}</version>
  46.       </dependency>
  47.       <dependency>
  48.          <groupId>log4j</groupId>
  49.          <artifactId>log4j</artifactId>
  50.          <version>${log4j.version}</version>
  51.       </dependency>
  52.       <dependency>
  53.             <groupId>org.slf4j</groupId>
  54.             <artifactId>slf4j-api</artifactId>
  55.             <version>${slf4j.version}</version>
  56.         </dependency>
  57.         <dependency>
  58.             <groupId>org.slf4j</groupId>
  59.             <artifactId>slf4j-log4j12</artifactId>
  60.             <version>${slf4j.version}</version>
  61.         </dependency>
  62.    </dependencies>
  63. </project>

 

在applicationContext.xml增加mongodb.properties:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xmlns:cache="http://www.springframework.org/schema/cache"
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  8.                         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  9.                         http://www.springframework.org/schema/context
  10.                         http://www.springframework.org/schema/context/spring-context-4.2.xsd
  11.                         http://www.springframework.org/schema/mvc
  12.                         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
  13.                         http://www.springframework.org/schema/cache
  14.                         http://www.springframework.org/schema/cache/spring-cache-4.2.xsd ">
  15.  
  16.  
  17.     <context:component-scan base-package="com.zjf.*" />
  18.  
  19.    <!-- 属性文件位置 -->
  20.     <bean id="annotationPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  21.         <property name="locations">
  22.             <list>
  23.                 <value>classpath:config/properties/mongodb.properties</value>
  24.                 <value>classpath:config/properties/redis.properties</value>
  25.             </list>
  26.         </property>
  27.     </bean>
  28.  
  29.  
  30. </beans>

mongodb.properties:

  1. mongo.hostport=192.168.1.101:27017
  2. mongo.connectionsPerHost=8
  3. mongo.threadsAllowedToBlockForConnectionMultiplier=4
  4. #\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
  5. mongo.connectTimeout=1000
  6. #\u7B49\u5F85\u65F6\u95F4
  7. mongo.maxWaitTime=1500
  8. mongo.autoConnectRetry=true
  9. mongo.socketKeepAlive=true
  10. #Socket\u8D85\u65F6\u65F6\u95F4
  11. mongo.socketTimeout=1500
  12. mongo.slaveOk=true

 

 

增加mongodb.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  4.    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
  5.    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
  6.     http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
  7.    http://www.springframework.org/schema/beans
  8.    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
  9.  
  10.    <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
  11.    <mongo:mongo id="mongo" replica-set="${mongo.hostport}">
  12.       <!-- 一些连接属性的设置 -->
  13.       <mongo:options connections-per-host="${mongo.connectionsPerHost}"
  14.          threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
  15.          connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"
  16.          auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}"
  17.          socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}"
  18.          write-number="1" write-timeout="0" write-fsync="true" />
  19.    </mongo:mongo>
  20.    <!-- dbname是要操作的数据库 -->
  21.    <mongo:db-factory id="myMongoDbFactory" dbname="mydb" mongo-ref="mongo" />
  22.  
  23.    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  24.       <constructor-arg name="mongoDbFactory" ref="myMongoDbFactory" />
  25.    </bean>
  26.  
  27. </beans>

 

上面的各种参数说明:

参数列表如下:



#控制系统在发生连接错误时是否重试 ,默以为false --boolean

mongo.options.autoConnectRetry=false

#每个主机答应的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住 ,默以为10 --int

mongo.options.connectionsPerHost=10

#multiplier for connectionsPerHost for # of threads that can block if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block more than that and an exception will be throw --int

mongo.options.threadsAllowedToBlockForConnectionMultiplier=5

#被阻塞线程从连接池获取连接的最长等待时间(ms) --int

mongo.options.maxWaitTime 

#在建立(打开)套接字连接时的超时时间(ms),默以为0(无穷) --int

mongo.options.connectTimeout=0

#套接字超时时间;该值会被传递给Socket.setSoTimeout(int)。默以为0(无穷) --int

mongo.options.socketTimeout=0

#This controls whether or not to have socket keep alive turned on (SO_KEEPALIVE). defaults to false --boolean

mongo.options.socketKeepAlive=false

#Override the DBCallback factory. Default is for the standard Mongo Java driver configuration --DBCallbackFactory

mongo.options.dbCallbackFactory 

#//指明是否答应驱动从次要节点或者奴隶节点读取数据,默以为false --boolean

mongo.options.slaveOk=false

#假如为true,驱动每次update后会发出一个getLastError命令来保证成功,默以为false --boolean

mongo.options.safe=false 

#If set, the w value of WriteConcern for the connection is set to this. Defaults to 0; implies safe = true --int

mongo.options.w=0

#If set, the wtimeout value of WriteConcern for the connection is set to this. Defaults to 0; implies safe = true --int

mongo.options.wtimeout=0

#Sets the fsync value of WriteConcern for the connection. Defaults to false; implies safe = true --boolean

mongo.options.fsync=false

 

配置已经完成,我们来看一下java代码的目录结构:

 

主要看model和daoimpl的代码。贴出如下:

  1. package com.zjf.spring.mongodb.model;
  2.  
  3. import org.springframework.data.mongodb.core.mapping.Document;
  4. //将student映射为Mongodb数据库中的一个名字叫student的collection
  5. @Document(collection="student")
  6. public class Student {
  7.  
  8.    private String id;
  9.  
  10.    private String name;
  11.  
  12.    private int age;
  13.  
  14.    public String getId() {
  15.       return id;
  16.    }
  17.  
  18.    public void setId(String id) {
  19.       this.id = id;
  20.    }
  21.  
  22.    public String getName() {
  23.       return name;
  24.    }
  25.  
  26.    public void setName(String name) {
  27.       this.name = name;
  28.    }
  29.  
  30.    public int getAge() {
  31.       return age;
  32.    }
  33.  
  34.    public void setAge(int age) {
  35.       this.age = age;
  36.    }
  37.  
  38.    @Override
  39.    public String toString() {
  40.       return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
  41.    }
  42.  
  43.  
  44. }

 

 

  1. package com.zjf.spring.mongodb.dao.impl;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.mongodb.core.MongoOperations;
  8. import org.springframework.data.mongodb.core.query.Criteria;
  9. import org.springframework.data.mongodb.core.query.Query;
  10. import org.springframework.data.mongodb.core.query.Update;
  11. import org.springframework.stereotype.Repository;
  12.  
  13. import com.mongodb.WriteResult;
  14. import com.zjf.spring.mongodb.dao.StudentDao;
  15. import com.zjf.spring.mongodb.model.Student;
  16.  
  17. //持久层注解
  18. @Repository
  19. public class StudentDaoImpl implements StudentDao {
  20.  
  21.    //引入mongo.xml中配置的mongoTemplate
  22.    @Autowired
  23.    private MongoOperations mongoTemplate;
  24.  
  25.    public void add(Student student)
  26.    {
  27.       this.mongoTemplate.insert(student);
  28.    }
  29.  
  30.    public Student getById(String id)
  31.    {
  32.       return this.mongoTemplate.findById(id, Student.class);
  33.    }
  34.  
  35.    public void modify(Student student)
  36.    {
  37.       this.mongoTemplate.save(student);
  38.    }
  39.  
  40.    public void delete(Student student)
  41.    {
  42.       this.mongoTemplate.remove(student);
  43.    }
  44.  
  45.    public void deleteById(String id)
  46.    {
  47.       this.mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), Student.class);
  48.    }
  49.  
  50.    //一个根据名字查询结果的方法
  51.    @Override
  52.    public List<Student> getByName(String name) {
  53.       List<Student> students = new ArrayList<Student>();
  54.       Query query = new Query();
  55.         query.addCriteria(new Criteria("name").is(name));
  56.         students = this.mongoTemplate.find(query, Student.class);
  57.       return students;
  58.    }
  59.    ////一个根据名字更新数据方法
  60.    @Override
  61.    public int updateByName(String name) {
  62.       int n = 0;
  63.       List<Student> students = new ArrayList<Student>();
  64.       Query query = new Query();
  65.         query.addCriteria(new Criteria("name").is(name));
  66.         Update update = new Update();
  67.         update.set("name", "xhj");
  68.       WriteResult result = this.mongoTemplate.updateMulti(query, update, Student.class);
  69.       n = result.getN();
  70.       return n;
  71.    }
  72.  
  73. }

posted on 2017-06-05 01:21  张小贱1987  阅读(455)  评论(0编辑  收藏  举报

导航