Spring Mongodb集成

Maven的安装及使用等,请参考我的其它文章,费话不多说,先添加依赖:

pom.xml

<properties>
		<org.springframework.version>3.0.7.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		
		<!-- spring core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<!-- spring core -->
		
		<!-- mongodb -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>
		<!-- mongodb -->
		
		<!-- mongodb spring -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.1.1.RELEASE</version>
		</dependency>
		<!-- mongodb spring -->
		
		<!-- log -->
		<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
		<!-- log -->
	</dependencies>

配置数据源:

mongodb.properties

mongo.connectionsPerHost=4
mongo.threadsAllowedToBlockForConnectionMultiplier=20
mongo.connectTimeout=0
mongo.maxWaitTime=10000
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
mongo.socketTimeout=0

applicationContext-datasource.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:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<context:property-placeholder location="classpath*:mongodb.properties"/>
	
	<!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
	<mongo:mongo id="mongo" replica-set="192.168.1.17:27017">
		<!-- 一些连接属性的设置 -->	
		<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}"
		     write-number="1"
		     write-timeout="0"
		     write-fsync="true"/>
	</mongo:mongo>

	<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
	<mongo:db-factory dbname="mymongo" mongo-ref="mongo"/>

	<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
	  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
	</bean>
</beans>
model类:

Student.java

/**
 * 
 */
package com.versou.mongodb.model;

import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author hadoop
 *
 */
@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;
	}
}

Dao层:

StudentDao.java

/**
 * 
 */
package com.versou.mongodb.dao;

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 com.versou.mongodb.model.Student;

/**
 * @author hadoop
 *
 */
public class StudentDao {
	
	@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);
	}
}

service层:

StudentService.java

package com.versou.mongodb.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.versou.mongodb.dao.StudentDao;
import com.versou.mongodb.model.Student;

public class StudentService {
	
	@Autowired
	private StudentDao studentDao;
	
	public void add(Student student)
	{
		this.studentDao.add(student);
	}
	
	public Student getById(String id)
	{
		return this.studentDao.getById(id);
	}
	
	public void modify(Student student)
	{
		this.studentDao.modify(student);
	}
	
	public void delete(Student student)
	{
		this.studentDao.delete(student);
	}
	
	public void deleteById(String id)
	{
		this.studentDao.deleteById(id);
	}
}

applicationContext-bean.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:mvc="http://www.springframework.org/schema/mvc" 
	 xmlns:aop="http://www.springframework.org/schema/aop" 
	 xmlns:tx="http://www.springframework.org/schema/tx" 
	 xmlns:context="http://www.springframework.org/schema/context" 
	 xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx        
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd      
		http://www.springframework.org/schema/aop      
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">       
    
    <!-- 自动扫描 -->
    <context:annotation-config/>
   	
   	<bean id="studentDao" class="com.versou.mongodb.dao.StudentDao"></bean>
   	
	<bean id="studentService" class="com.versou.mongodb.service.StudentService"></bean>
</beans>

我们测试下插入1000条数据的用时:

public class AppMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{"classpath:applicationContext-bean.xml", "classpath:applicationContext-datasource.xml"});
		StudentService studentService = ctx.getBean("studentService", StudentService.class);
		/*Student student = new Student();
		student.setName("mingli");
		student.setAge(20);
		studentDao.add(student);*/
		/*Student student = studentDao.getById("518de7daf669a6f1e68746a7");
		System.out.println(student.getAge());*/
		/*studentDao.deleteById("518de7daf669a6f1e68746a7");*/
		long startTime = System.currentTimeMillis();
		for(int i = 0; i < 1000; i++)
		{
			Student student = new Student();
			student.setName("mingli");
			student.setAge(20);
			studentService.add(student);
		}
		long endTime = System.currentTimeMillis();
		System.out.println(endTime - startTime);
	}

}

输出如下:

INFO [org.springframework.context.support.FileSystemXmlApplicationContext] - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@378f6235: startup date [Sun May 12 09:50:22 CST 2013]; root of context hierarchy
INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [applicationContext-bean.xml]
INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [applicationContext-datasource.xml]
INFO [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from URL [file:/D:/java-space2/mongodb/target/classes/mongodb.properties]
INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6ee0a386: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,studentDao,studentService,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,mongo,org.springframework.beans.factory.config.CustomEditorConfigurer#0,org.springframework.beans.factory.config.CustomEditorConfigurer#1,org.springframework.beans.factory.config.CustomEditorConfigurer#2,mongoDbFactory,mongoTemplate]; root of factory hierarchy
36992

在mongodb是进行查看,我们数据格式如下:

Spring Mongodb集成_第1张图片

可以看到,spring默认给我们加一列_class。

id映射成_id,name,age没有改变。



你可能感兴趣的:(spring,mongodb)