Spring MVC + Mongodb
在maven的pom.xml中增加引用:
-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
<modelVersion>4.0.0</modelVersion>
-
<groupId>com.zjf</groupId>
-
<artifactId>springmvc</artifactId>
-
<version>0.0.1-SNAPSHOT</version>
-
<packaging>war</packaging>
-
-
<properties>
-
<spring.webmvc.version>4.3.0.RELEASE</spring.webmvc.version>
-
<junit.version>4.8.2</junit.version>
-
<jedis.version>2.8.1</jedis.version>
-
<log4j.version>1.2.16</log4j.version>
-
<slf4j.version>1.7.2</slf4j.version>
-
<spring.data.redis.version>1.7.2.RELEASE</spring.data.redis.version>
-
<spring.data.mongodb.version>1.8.0.RELEASE</spring.data.mongodb.version>
-
</properties>
-
-
-
<dependencies>
-
<dependency>
-
<groupId>junit</groupId>
-
<artifactId>junit</artifactId>
-
<version>${junit.version}</version>
-
<scope>test</scope>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework</groupId>
-
<artifactId>spring-webmvc</artifactId>
-
<version>${spring.webmvc.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>redis.clients</groupId>
-
<artifactId>jedis</artifactId>
-
<version>${jedis.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.data</groupId>
-
<artifactId>spring-data-redis</artifactId>
-
<version>${spring.data.redis.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.data</groupId>
-
<artifactId>spring-data-mongodb</artifactId>
-
<version>${spring.data.mongodb.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>log4j</groupId>
-
<artifactId>log4j</artifactId>
-
<version>${log4j.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>org.slf4j</groupId>
-
<artifactId>slf4j-api</artifactId>
-
<version>${slf4j.version}</version>
-
</dependency>
-
<dependency>
-
<groupId>org.slf4j</groupId>
-
<artifactId>slf4j-log4j12</artifactId>
-
<version>${slf4j.version}</version>
-
</dependency>
-
</dependencies>
-
</project>
在applicationContext.xml增加mongodb.properties:
-
<?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"
-
xmlns:cache="http://www.springframework.org/schema/cache"
-
xsi:schemaLocation="http://www.springframework.org/schema/beans
-
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
-
http://www.springframework.org/schema/context
-
http://www.springframework.org/schema/context/spring-context-4.2.xsd
-
http://www.springframework.org/schema/mvc
-
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
-
http://www.springframework.org/schema/cache
-
http://www.springframework.org/schema/cache/spring-cache-4.2.xsd ">
-
-
-
<context:component-scan base-package="com.zjf.*" />
-
-
<!-- 属性文件位置 -->
-
<bean id="annotationPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
-
<property name="locations">
-
<list>
-
<value>classpath:config/properties/mongodb.properties</value>
-
<value>classpath:config/properties/redis.properties</value>
-
</list>
-
</property>
-
</bean>
-
-
-
</beans>
mongodb.properties:
-
mongo.hostport=192.168.1.101:27017
-
mongo.connectionsPerHost=8
-
mongo.threadsAllowedToBlockForConnectionMultiplier=4
-
#\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
-
mongo.connectTimeout=1000
-
#\u7B49\u5F85\u65F6\u95F4
-
mongo.maxWaitTime=1500
-
mongo.autoConnectRetry=true
-
mongo.socketKeepAlive=true
-
#Socket\u8D85\u65F6\u65F6\u95F4
-
mongo.socketTimeout=1500
-
mongo.slaveOk=true
增加mongodb.xml:
-
<?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:jdbc="http://www.springframework.org/schema/jdbc"
-
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
-
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
-
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
-
http://www.springframework.org/schema/beans
-
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
-
-
<!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
-
<mongo:mongo id="mongo" replica-set="${mongo.hostport}">
-
<!-- 一些连接属性的设置 -->
-
<mongo:options connections-per-host="${mongo.connectionsPerHost}"
-
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
-
connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"
-
auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}"
-
socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}"
-
write-number="1" write-timeout="0" write-fsync="true" />
-
</mongo:mongo>
-
<!-- dbname是要操作的数据库 -->
-
<mongo:db-factory id="myMongoDbFactory" dbname="mydb" mongo-ref="mongo" />
-
-
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
-
<constructor-arg name="mongoDbFactory" ref="myMongoDbFactory" />
-
</bean>
-
-
</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的代码。贴出如下:
-
package com.zjf.spring.mongodb.model;
-
-
import org.springframework.data.mongodb.core.mapping.Document;
-
//将student映射为Mongodb数据库中的一个名字叫student的collection
-
@Document(collection="student")
-
public class Student {
-
-
private String id;
-
-
private String name;
-
-
private int age;
-
-
public String getId() {
-
return id;
-
}
-
-
public void setId(String id) {
-
this.id = id;
-
}
-
-
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 "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
-
}
-
-
-
}
-
package com.zjf.spring.mongodb.dao.impl;
-
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.data.mongodb.core.MongoOperations;
-
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.Repository;
-
-
import com.mongodb.WriteResult;
-
import com.zjf.spring.mongodb.dao.StudentDao;
-
import com.zjf.spring.mongodb.model.Student;
-
-
//持久层注解
-
@Repository
-
public class StudentDaoImpl implements StudentDao {
-
-
//引入mongo.xml中配置的mongoTemplate
-
@Autowired
-
private MongoOperations mongoTemplate;
-
-
public void add(Student student)
-
{
-
this.mongoTemplate.insert(student);
-
}
-
-
public Student getById(String id)
-
{
-
return this.mongoTemplate.findById(id, Student.class);
-
}
-
-
public void modify(Student student)
-
{
-
this.mongoTemplate.save(student);
-
}
-
-
public void delete(Student student)
-
{
-
this.mongoTemplate.remove(student);
-
}
-
-
public void deleteById(String id)
-
{
-
this.mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), Student.class);
-
}
-
-
//一个根据名字查询结果的方法
-
@Override
-
public List<Student> getByName(String name) {
-
List<Student> students = new ArrayList<Student>();
-
Query query = new Query();
-
query.addCriteria(new Criteria("name").is(name));
-
students = this.mongoTemplate.find(query, Student.class);
-
return students;
-
}
-
////一个根据名字更新数据方法
-
@Override
-
public int updateByName(String name) {
-
int n = 0;
-
List<Student> students = new ArrayList<Student>();
-
Query query = new Query();
-
query.addCriteria(new Criteria("name").is(name));
-
Update update = new Update();
-
update.set("name", "xhj");
-
WriteResult result = this.mongoTemplate.updateMulti(query, update, Student.class);
-
n = result.getN();
-
return n;
-
}
-
-
}