首页 > 代码库 > Spring MVC + Mongodb

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>

配置已经完成,我们来看一下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. }

Spring MVC + Mongodb