首页 > 代码库 > Spring整合MongoDB

Spring整合MongoDB

版本:

spring:4.1.3.RELEASE

mongo-java-driver.version:3.4.1

spring-data-mongodb.version:1.7.0.RELEASE


配置:

1、pom.xml中添加核心依赖(两个)

+++++++++++++++++++++++++++++++++++++++++++++++++++++

                <!-- mongo-java-dirver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>3.4.1</version>
		</dependency>
		<!-- spring-data-mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.7.0.RELEASE</version>
		</dependency>

++++++++++++++++++++++++++++++++++++++++++++++++++++++

完整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.fwmagic.mongo</groupId>
	<artifactId>fwmagic-mongo</artifactId>
	<version>1.0.0-SNAPSHOT</version>

	<properties>
		<junit.version>4.12</junit.version>
		<spring.version>4.1.3.RELEASE</spring.version>
		<fastjson.version>1.2.15</fastjson.version>
		<slf4j.version>1.6.4</slf4j.version>
		<joda-time.version>2.5</joda-time.version>
		<commons-lang3.version>3.3.2</commons-lang3.version>
		<commons-io.version>1.3.2</commons-io.version>
		<mongo-java-driver.version>3.4.1</mongo-java-driver.version>
		<spring-data-mongodb.version>1.7.0.RELEASE</spring-data-mongodb.version>

		<env>dev</env>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
	</properties>

	<dependencies>
		<!--junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>

		<!-- fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- slf4j日志 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- Apache工具组件 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${commons-lang3.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
		<!-- 时间操作组件 -->
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>${joda-time.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.0</version>
		</dependency>
		<!-- mongo-java-dirver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>${mongo-java-driver.version}</version>
		</dependency>
		<!-- spring-data-mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>${spring-data-mongodb.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 配置Tomcat插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<archiveClasses>true</archiveClasses>
					<packagingExcludes>WEB-INF/classes/**</packagingExcludes>
					<webResources>
						<resource>
							<directory>src/main/webapp/WEB-INF</directory>
							<includes>
								<include>applicationContext.xml</include>
							</includes>
							<filtering>true</filtering>
							<targetPath>WEB-INF</targetPath>
						</resource>
					</webResources>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.7.1</version>
			</plugin>
		</plugins>
	</build>
</project>


2、mongo.properties

####################################################
###MongoDB configuration
####################################################
mongo.host=localhost
mongo.port=27017
mongo.dbname=demodb
mongo.username=admin
mongo.password=123456
#一个线程变为可用的最大阻塞数
mongo.connectionsPerHost=8
#线程队列数,它与以上面connectionsPerHost值相乘的结果就是线程队列最大值
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间(毫秒) 
mongo.connectTimeout=1500
#最大等待时间
mongo.maxWaitTime=1500
#自动重连
mongo.autoConnectRetry=true
#scoket保持活动
mongo.socketKeepAlive= true
#scoket超时时间
mongo.socketTimeout=1500
#读写分离
mongo.slaveOk=true


3、applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
        
	<!--配置service的包扫描,自动注入Service -->
	<context:component-scan base-package="com.fwmagic" />

	<!-- 使用spring自带的占位符替换功能 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- 允许JVM参数覆盖 -->
		<property name="systemPropertiesModeName" value="http://www.mamicode.com/SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<!-- 忽略没有找到的资源文件 -->
		<property name="ignoreResourceNotFound" value="http://www.mamicode.com/true" />
		<!-- 配置资源文件 -->

		<property name="locations">
			<list>
				<value>classpath:mongo.properties</value>
				<value>classpath:log4j.properties</value>
			</list>
		</property>
	</bean>
	
		<!--credentials的配置形式是:用户名:密码@默认数据库 -->
	<mongo:mongo-client id="mongoClient" host="${mongo.host}"
		port="${mongo.port}" credentials="${mongo.username}:${mongo.password}@${mongo.dbname}">
		<mongo:client-options write-concern="SAFE"
			connections-per-host="${mongo.connectionsPerHost}"
			threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
			connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"
			socket-timeout="${mongo.socketTimeout}" />
	</mongo:mongo-client>

	<mongo:db-factory id="mongoDbFactory" dbname="${mongo.dbname}"
		mongo-ref="mongoClient" />

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean>
</beans>


单元测试:

package com.fwmagic.dao;

import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
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.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.fwmagic.pojo.Notice;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext*.xml")
public class NoticeDAOTest {

	@Autowired
	private NoticeDAO dao;
	
	/**
	 * 查询所有文档
	 */
	@Test
	public void testList() {
		Query query = new Query();
		List<Notice> notice = dao.list(query, Notice.class);
		for (Notice n : notice) {
			System.out.println(n);
		}
	}

	/**
	 * 插入文档
	 */
	@Test
	public void testInsert(){
		Notice notice = new Notice();
		notice.setSiteId(7);
		notice.setCreator("diaochan");
		notice.setTitle("今天星期一");
		notice.setUpdateTime(new Date());
		dao.insert(notice);
	}
	
	/**
	 * 更新文档
	 */
	@Test
	public void testUpdate(){
		Criteria criteria = new Criteria();
		criteria.and("creator").is("zhaojun");
		Query query = new Query(criteria);
		dao.update(query, Update.update("createTime", new Date()), Notice.class);
	}
	
	/**
	 * 删除一行文档
	 */
	@Test
	public void testRemove(){
		Criteria criteria = new Criteria();
		criteria.and("creator").is("zhaojun");
		Query query = new Query(criteria);
		dao.remove(query, Notice.class);
	}
	
	//未完待续……
}


NoticeDAO.java

package com.fwmagic.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.fwmagic.pojo.Notice;
import com.mongodb.WriteResult;

@Repository
public class NoticeDAO implements BaseDAO<Notice>{

	@Autowired
	private MongoTemplate mt;
	
	@Override
	public List<Notice> list(Query query, Class<Notice> entityClass) {
		return mt.find(query, entityClass);
	}

	@Override
	public Notice findOne(Query query, Class<Notice> entityClass) {
		return mt.findOne(query, entityClass);
	}
	
	@Override
	public void insert(Notice notice){
		mt.insert(notice);
	}
	
	@Override
	public WriteResult update(Query query, Update update, Class<?> entityClass){
		return mt.updateFirst(query, update, entityClass);
	}
	
	@Override
	public void remove(Query query, Class<?> entityClass){
		mt.remove(query, entityClass);
	}
}


完整demo请移步此处查看.

本文出自 “SimpleLife” 博客,请务必保留此出处http://simplelife.blog.51cto.com/9954761/1932408

Spring整合MongoDB