欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring与MongoDB整合 博客分类: MongoDBSpring mongodbspring 

程序员文章站 2024-03-21 23:48:52
...

可在*仓库下载:

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);
	}
	
    
}

 

 

 

相关标签: mongodb spring