Spring与MongoDB整合

可在中央仓库下载:

spring-data-commons-1.11.0.jar

spring-data-mongodb-1.8.1.jar

mongo-2.10.1.jar

spring-XX-4.0.6.jar

以上包的版本需要相应版本的spring和mongoDB驱动,否则会出现各种ClassNotFoundException。

 

在spring的beans.xml中添加(mongoTemplate的构造方法还有mongoDbFactory方式):

 

xmlns:mongo="http://www.springframework.org/schema/data/mongo"
...
http://www.springframework.org/schema/data/mongo    
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
...

       <mongo:mongo host="localhost" port="27017"/> 

       <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 
           <constructor-arg ref="mongo"/> 
           <constructor-arg name="databaseName" value="db"/> 
        </bean>

 

 

service实现层调用

 

package com.edus.service.impl.demo;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
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.Service;

import com.edus.common.Book;
import com.edus.service.demo.IMongoDemoService;

@Service("mongoDemoService")
public class MongoDemoServiceImpl implements IMongoDemoService {

	public static final String COLLECTION_NAME = "demo";
	
	@Resource
	private MongoTemplate mongoTemplate;

	@Override
	public Book delBookInMongo(Integer id) {
		return mongoTemplate.findAndRemove(new Query(Criteria.where("id").is(id)), Book.class, COLLECTION_NAME);
	}

	@Override
	public List<Book> findBookListInMongo(Map<String, Object> args) {
		return mongoTemplate.findAll(Book.class, COLLECTION_NAME);//无条件查询
	}

	@Override
	public void saveBookInMongo(Book book) {
		mongoTemplate.save(book, COLLECTION_NAME);
	}

	@Override
	public Book updateBookInMongo(Book book) {
		return mongoTemplate.findAndModify(new Query(Criteria.where("id").is(book.getId())), new Update().set("name", book.getName()).set("price", book.getPrice()), Book.class, COLLECTION_NAME);
	}
	
    
}

 

 

 

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