SpringMVC集成mongodb

本文详细介绍了如何在SpringMVC项目中集成MongoDB,包括pom文件的配置,spring-mongodb.xml的设置,底层方法的配置,对应collection的类编写,以及具体service的调用步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、pom文件配置

      <!-- spring-data-mongodb -->
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.10.6.RELEASE</version>
      </dependency>

二、配置spring-mongodb.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="mongo" class="com.mongodb.Mongo">
        <constructor-arg index="0" value="${zmxj.mongodb.host}" type="java.lang.String" />
        <constructor-arg index="1" value="${zmxj.mongodb.port}" type="int" />
    </bean>

    <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
        <constructor-arg index="0" value="${zmxj.mongodb.username}" />
        <constructor-arg index="1" value="${zmxj.mongodb.password}" />
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg index="0" ref="mongo" />
        <constructor-arg index="1" value="zmxj" type="java.lang.String" />
        <constructor-arg index="2" ref="userCredentials" />
    </bean>

</beans>

三、配置底层方法

package com.zmgj.zmxj.mongo;

import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
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 java.util.List;

/**
 * Created by syk on 2017/8/25.
 */
public abstract class BaseRepository<T> {

    @Autowired
    protected MongoTemplate mongoTemplate;

    /**
     * 获取集合的所有文档
     */
    public List<T> getAlls(Class<T> collectionClass) {
        return mongoTemplate.findAll(collectionClass);
    }

    /**
     * 根据特定条件查询指定字段的集合
     * @param queryObject 查询条件
     * @param fieldsObject 返回指定字段
     * @param collectionClass
     * @return
     */
    public List<T> getByCondition(DBObject queryObject, DBObject fieldsObject,  Class<T> collectionClass) {
        Query query = new BasicQuery(queryObject, fieldsObject);
        return mongoTemplate.find(query, collectionClass);
    }

    /**
     * 根据特定条件查询集合
     * @param queryObject 查询条件
     * @param collectionClass
     * @return
     */
    public T getByCondition(DBObject queryObject, Class<T> collectionClass) {
        Query query = new BasicQuery(queryObject);
        return mongoTemplate.findOne(query, collectionClass);
    }

    /**
     * 保存一个文档到集合
     */
    public void save(T t) {
        mongoTemplate.insert(t);
    }

    /**
     * 根据id获取一个文档
     */
    public T getById(String id,Class<T> collectionClass) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),collectionClass);
    }

    /**
     * 更新文档
     * @param idProperty 唯一标识的属性
     * @param id 唯一标识的值
     * @param propertyName 要修改的属性名
     * @param propertyValue 要修改的属性值
     * @param collectionClass 集合对应的bean
     * @return
     */
    public WriteResult update(String idProperty, String id, String propertyName, String propertyValue, Class<T> collectionClass) {
        return mongoTemplate.updateFirst(
                new Query(Criteria.where(idProperty).is(id)),
                Update.update(propertyName, propertyValue), collectionClass);
    }

    /**
     * 根据Id删除文档
     */
    public void deleteById(String id,Class<T> collectionClass) {
        mongoTemplate.remove(new Query(Criteria.where("id").is(id)), collectionClass);
    }

    /**
     * 根据传入参数删除文档
     * @param paramName 参数名
     * @param paramValue 参数值
     * @param collectionClass
     */
    public void deleteByParam(String paramName, Object paramValue, Class<T> collectionClass) {
        mongoTemplate.remove(new Query(Criteria.where(paramName).is(paramValue)), collectionClass);
    }

    /**
     * 创建集合
     */
    public void createCollection(Class<T> collectionClass) {
        if (!mongoTemplate.collectionExists(collectionClass)) {
            mongoTemplate.createCollection(collectionClass);
        }
    }

    /**
     * 删除集合
     */
    public void dropCollection(Class<T> collectionClass) {
        if (mongoTemplate.collectionExists(collectionClass)) {
            mongoTemplate.dropCollection(collectionClass);
        }
    }

    /**
     * 获取mongoTemplate,想干什么就能干什么,他是操作mongodb的入口
     * @return
     */
    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

    /**
     * 帮助继承者注入资源
     * @param mongoTemplate
     */
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

}

四、编写与mongodb对应collection的类

package com.zmgj.zmxj.mongo;

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

import java.util.Date;

/**
 * Created by syk on 2017/8/25.
 */
@Document(collection = "book_chapter")
public class BookChapter {

    @Id
    private String id;
    private Integer bookId;
    private Integer chapterId;
    private String chapterNumber;
    private String chapterName;
    private String chapterContent;
    private Integer chapterLength;
    private Date createTime;
    private Date updateTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public Integer getChapterId() {
        return chapterId;
    }

    public void setChapterId(Integer chapterId) {
        this.chapterId = chapterId;
    }

    public String getChapterNumber() {
        return chapterNumber;
    }

    public void setChapterNumber(String chapterNumber) {
        this.chapterNumber = chapterNumber;
    }

    public String getChapterName() {
        return chapterName;
    }

    public void setChapterName(String chapterName) {
        this.chapterName = chapterName;
    }

    public String getChapterContent() {
        return chapterContent;
    }

    public void setChapterContent(String chapterContent) {
        this.chapterContent = chapterContent;
    }

    public Integer getChapterLength() {
        return chapterLength;
    }

    public void setChapterLength(Integer chapterLength) {
        this.chapterLength = chapterLength;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

五、具体service调用

package com.zmgj.zmxj.service.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.zmgj.zmxj.mongo.BaseRepository;
import com.zmgj.zmxj.mongo.BookChapter;
import com.zmgj.zmxj.service.IBookChapterService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

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

/**
 * Created by syk on 2017/8/25.
 */
@Service
public class BookChapterServiceImpl extends BaseRepository<BookChapter> implements IBookChapterService,InitializingBean {

    final static Logger logger = LoggerFactory.getLogger(BookChapterServiceImpl.class);

    @Override
    public void insertBookChapter(Integer bookId, String book) {
        try {
            BookChapter bookChapter = new BookChapter();
            bookChapter.setBookId(bookId);
            bookChapter.setChapterId(1);
            bookChapter.setChapterName(chapterName);
            bookChapter.setChapterNumber(chapterNumber);
            bookChapter.setChapterContent(chapterContent);
            bookChapter.setChapterLength(chapterContent.getBytes().length);
            // 获取系统时间
            Date now = new Date();
            bookChapter.setCreateTime(now);
            bookChapter.setUpdateTime(now);
            save(bookChapter);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public BookChapter selectById(String id) {
        return getById(id, BookChapter.class);
    }

    @Override
    public List<BookChapter> selectByBookId(Integer bookId) {
        DBObject dbObject = new BasicDBObject();
        // 查询条件
        dbObject.put("bookId", bookId);
        BasicDBObject fieldsObject = new BasicDBObject();
        // 指定返回的字段
        fieldsObject.put("_id", true);
        fieldsObject.put("bookId", true);
        fieldsObject.put("chapterId", true);
        fieldsObject.put("chapterNumber", true);
        fieldsObject.put("chapterName", true);
        fieldsObject.put("chapterLength", true);
        return getByCondition(dbObject, fieldsObject, BookChapter.class);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(!this.mongoTemplate.collectionExists(BookChapter.class)){
            this.mongoTemplate.createCollection(BookChapter.class);
        }
    }

    @Override
    public BookChapter selectByChapterId(Integer bookId, Integer chapterId) {
        DBObject dbObject = new BasicDBObject();
        // 查询条件
        dbObject.put("bookId", bookId);
        dbObject.put("chapterId", chapterId);
        return getByCondition(dbObject, BookChapter.class);
    }

    @Override
    public void deleteByBookId(String paramName, Integer bookId) {
        deleteByParam(paramName, bookId, BookChapter.class);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值