mongodb与spring集成案例

假设现在我们已经安装好了mongodb,并且都熟悉spring项目的配置。

spring 配置文件 spring-context.xml

与mongodb不相关的配置都已经去掉

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                        http://www.springframework.org/schema/task 
                        http://www.springframework.org/schema/task/spring-task-3.0.xsd
                        http://www.springframework.org/schema/data/mongo 
						http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
						http://www.springframework.org/schema/mvc 
        				http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        ">
	<context:property-placeholder
		ignore-resource-not-found="false" location="classpath:mongodb.properties" />
	
	<bean class="com.qing.utils.PropertyUtils">
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreResourceNotFound" value="false" />
		<property name="locations">
			<list>
				<value>classpath*:/mongodb.properties</value>
			</list>
		</property>
	</bean>

    <context:component-scan base-package="com.qing"/>
    <mongo:mongo id="mongo" replica-set="${mongo.host}">
        <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>  
    
	<mongo:db-factory id="mongoDbFactory" dbname="${mongo.database}" mongo-ref="mongo" username="${mongo.username}" password="${mongo.password}"/>
		
	<mongo:mapping-converter id="mongoConverter" base-package="com.qing.core.entity">
		<mongo:custom-converters base-package="com.qing.core.entity" />
	</mongo:mapping-converter>

	<bean id="nearest" class="com.mongodb.TaggableReadPreference.NearestReadPreference"/>
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg ref="mongoDbFactory" />
		<constructor-arg ref="mongoConverter" />
		<property name="writeConcern" value="SAFE" />
		<property name="readPreference" ref="nearest" />
	</bean>
	<mongo:repositories base-package="com.qing.core.repository" /> 

</beans>

mongodb.properties的属性配置文件

#The number of connections per host agreed, when the connection pool is used up, will be blocked, the default value is 10 --int
mongo.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.threadsAllowedToBlockForConnectionMultiplier=5
#Blocked thread connections from the connection pool gets the longest waiting time (MS) --int
mongo.maxWaitTime=0
#To establish a socket connection when timeout (MS), the default value is 0 (infinite)
mongo.connectTimeout=0
#Whether the control system in the event of a connection error retry,Defaults to false
mongo.autoConnectRetry=false
#This controls whether or not to have socket keep alive turned on (SO_KEEPALIVE). defaults to false --boolean
mongo.socketKeepAlive=false
#Socket timeout; this value will be passed to the Socket.setSoTimeout (int). The default value is 0 (infinite) --int
mongo.socketTimeout=0
#Indicates whether the promised to drive from the secondary nodes or the slave node reads the data, defaults to false
mongo.slaveOk=false

mongo.database=mongodbtest
mongo.host=192.168.23.4:27017
mongo.username=mongo
mongo.password=123456

编写实体类、Controller、Service、Dao相关 

实体类

import java.math.BigInteger;

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

@Document(collection = "student")
public class Student extends BaseDocument<BigInteger> implements Comparable<Student> {

	private static final long serialVersionUID = -3711325228602088792L;
	
	@Field("userId")
	private String userId;
	
	@Field("userName")
	private String userName;
	
	@Field("password")
	private String password;
	
	@Field("mobilPhone")
	private String mobilPhone;
	
	/////////get/set方法省略///////
	@Override
	public int compareTo(Student o) {
		if (o == null)
			return -1;
		return this.userId.compareTo(o.getUserId());
	}
}
import java.io.Serializable;

import org.springframework.data.annotation.Id;

/**
 * <p> 抽象实体基类,提供统一的ID,和相关的基本功能方法
 */
public abstract class BaseDocument<ID extends Serializable> extends AbstractDocument<ID> {

	@Id
	private ID id;
	@Override
    public ID getId() {
        return id;
    }

    @Override
    public void setId(ID id) {
        this.id = id;
    }

}
import java.io.Serializable;

/**
 * 抽象实体基类
 */
public abstract class AbstractDocument<ID extends Serializable> implements Serializable  {

	/**
	 * Returns the identifier of the document.
	 * 
	 * @return the id
	 */
	public abstract ID getId();
	/**
     * Sets the id of the document.
     *
     * @param id the id to set
     */
	public abstract void setId(final ID id);

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}

		if (this.getId() == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
			return false;
		}

		AbstractDocument<?> that = (AbstractDocument<?>) obj;

		return this.getId().equals(that.getId());
	}

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return this.getId() == null ? 0 : this.getId().hashCode();
	}
}

dao

import java.math.BigInteger;
import java.util.List;

import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;

import com.qing.core.entity.Student;

public interface StudentRepository extends CrudRepository<Student, BigInteger>{
	
	List<Student> findByUserIdAndUserName(String userId,String userName);

	@Query("{userId:?0,$or:[{userName:{ $regex:?1}},{password:{ $regex:?1}}]}")
	List<Student> findStudentByUserIdAndUserName(String userId, String userName);
}

service

@Service
public class StudentService {

	@Autowired
	private StudentRepository studentRepository;
	
	@Autowired
	MongoTemplate mongoTemplate;

	public Message create(Student stu) {
		this.studentRepository.save(stu);
		Message message = new Message();
		message.setData(stu);
		return message;
	}

	public Message delete(Student stu) {
//		this.studentRepository.delete(stu);
		mongoTemplate.remove(new Query(Criteria.where("userName").is(stu.getUserName())), Student.class);
		Message message = new Message();
		message.setData(stu);
		return message;
	}
	
	public void update(Student stu) {
		Update update = new Update();
		update.set("password", stu.getPassword());
		mongoTemplate.updateFirst(new Query(Criteria.where("userId").is(stu.getUserId())), update, Student.class);
	}
	
	public List<Student> findByUserIdAndUserName(Student stu) {
		
		String userId = stu.getUserId();
		String userName = stu.getUserName();
		List<Student> studentList = studentRepository.findByUserIdAndUserName(userId, userName);
		
		return studentList;
	}
	
	public List<Student> findStudents(Student stu) {
		
		String userId = stu.getUserId();
		String userName = stu.getUserName();
		
		List<Student> studentList = studentRepository.findStudentByUserIdAndUserName(userId, userName);
		return studentList;
	}
}

controller

这个类就自己发挥写吧,就是springmvc的controller调用service层。

猜你喜欢

转载自zhanshi258.iteye.com/blog/2225970