返回顶部

收藏

spring MongoDB 集成crud操作(简单封装)

更多

这两天一直在学习mongodb,由于我的博客网站想把mysql替换成mongodb,为什么会有这样的冲动,我通过收集一些资料,关于mongodb 跟 mysql 的对比...发现性能上mongodb比上mysql是高出很多倍...无论是增,删,修,查的操作.....都比mysql效率好...但是,我也看到,mongodb是文档型数据库...做一些高级查询的时候就可能产生麻烦了..特别是做银行的数据操作时,如果出错..没得事务回滚...这些都是比较严重的问题...

分析过博客网站这整个系统,觉得还是比较适合用mongodb...对于一些表与表的关联查询,我可以用程序上去解决(这部分可能就麻烦了些,不过没关系)...所以我决定使用mongodb

下面:spring MongoDB 集成crud操作(简单封装) 开始正题了,同样也是pom.xml首先把项目的依赖都管理好,这次一样用junit用来做action的动作触发,看看项目结构图:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkfree</groupId>
    <artifactId>Mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.6</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-release</id>
            <name>Spring Maven Release Repository</name>
            <url>http://repo.springsource.org/libs-release</url>
        </repository>
    </repositories>
</project>

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" 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.1.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="127.0.0.1" port="27017" />
    <mongo:db-factory dbname="database" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <!-- <constructor-arg name="mongoConverter" ref="mappingConverter" /> -->
    </bean>
</beans>

framework-context.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: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.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- 扫描注解Bean -->
    <context:component-scan base-package="com.mkfree.**.service">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <context:component-scan base-package="com.mkfree.**.dao">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

</beans>

这样就配置成功了..看下面的java代码

MongodbBaseDao.java

package com.mkfree.framework.common.mongodb;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

public abstract class MongodbBaseDao{

    /**
     * spring mongodb 集成操作类 
     */
    protected MongoTemplate mongoTemplate;

    /**
     * 通过条件查询实体(集合)
     * 
     * @param query
     */
    public Listfind(Query query) {
        return mongoTemplate.find(query, this.getEntityClass());
    }

    /**
     * 通过一定的条件查询一个实体
     * 
     * @param query
     * @return
     */
    public T findOne(Query query) {
        return mongoTemplate.findOne(query, this.getEntityClass());
    }

    /**
     * 通过条件查询更新数据
     * 
     * @param query
     * @param update
     * @return
     */
    public void update(Query query, Update update) {
        mongoTemplate.upsert(query, update, this.getEntityClass());
    }

    /**
     * 保存一个对象到mongodb
     * 
     * @param bean
     * @return
     */
    public T save(T bean) {
        mongoTemplate.save(bean);
        return bean;
    }

    /**
     * 通过ID获取记录
     * 
     * @param id
     * @return
     */
    public T get(String id) {
        return mongoTemplate.findById(id, this.getEntityClass());
    }

    /**
     * 通过ID获取记录,并且指定了集合名(表的意思)
     * 
     * @param id
     * @param collectionName
     *            集合名
     * @return
     */
    public T get(String id, String collectionName) {
        return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
    }

    /**
     * 获取需要操作的实体类class
     * 
     * @return
     */
    protected abstract ClassgetEntityClass();

    /**
     * 注入mongodbTemplate
     * 
     * @param mongoTemplate
     */
    protected abstract void setMongoTemplate(MongoTemplate mongoTemplate);
}

ArticleDao.java

package com.mkfree.blog.dao;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.stereotype.Repository;

import com.mkfree.blog.domain.Article;
import com.mkfree.framework.common.mongodb.MongodbBaseDao;

/**
 * DAO层操作类
 * 
 * @author oyhk
 * 
 *         2013-1-21下午1:57:14
 */
@SuppressWarnings("static-access")
@Repository("ArticleDao")
public class ArticleDao extends MongodbBaseDao{

    /**
     * 通过条件去查询
     * 
     * @return
     */
    public Article findOne(Map params) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.where("id").is(params.get("id"));
        query.addCriteria(criteria);
        return super.findOne(query);
    }

    /**
     * 暂时通过ID去修改title
     * 
     * @param id
     * @param params
     */
    public void updateEntity(String id, Map params) {
        super.updateEntity(query(where("id").is(id)), update("title", params.get("title")));
    }

    @Autowired
    @Qualifier("mongoTemplate")
    @Override
    protected void setMongoTemplate(MongoTemplate mongoTemplate) {
        super.mongoTemplate = mongoTemplate;
    }

    @Override
    protected ClassgetEntityClass() {
        return Article.class;
    }

}

Article.java

package com.mkfree.blog.domain;

/**
 * 博客实体类
 * 
 * @author hk 2012-11-1 下午10:55:38
 */
public class Posts {
    private String id;// 博客ID
    private String title;// 博客标题
    private String content;// 博客内容

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

ArticleService.java

package com.mkfree.blog.service;

import java.util.Map;

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

import com.mkfree.blog.dao.ArticleDao;
import com.mkfree.blog.domain.Article;

@Service("articleService")
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    public Article findByid(String id) {
        return (Article) articleDao.get(id);
    }

    public Article findOne(Map params) {
        return this.articleDao.findOne(params);
    }

    public Article save(Article bean) {
        return (Article) articleDao.save(bean);
    }

    /**
     * 暂时只是固定去修改,会有下一篇博客,写高级修改...
     */
    public void update(String id, Map params) {
        this.articleDao.updateEntity(id, params);
    }
}

ArticleController.java

package com.mkfree.blog.action;

import java.util.HashMap;
import java.util.Map;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkfree.blog.domain.Article;
import com.mkfree.blog.service.ArticleService;

public class ArticleController {

    private static ApplicationContext app;
    private static ArticleService articleService;

    @Test
    public void save() {
        Article a = new Article();
        a.setTitle("mongodb开始实战");
        a.setContent("mongodb开始实战..内容");
        articleService.save(a);
        System.out.println(a);
    }

    @Test
    public void findArticle() {
        Article a = articleService.findByid("50fd0c36bc40ceec1a44308b");
        System.out.println(a);
    }

    @Test
    public void update() {
        Map params = new HashMap();
        params.put("title", "修改内容...");
        articleService.update("50fe23e6bc402ee4051f90b8", params);
    }

    @BeforeClass
    public static void initSpring() {
        app = new ClassPathXmlApplicationContext(new String[] { "classpath:spring/framework-context.xml",
                "classpath:spring/mongodb.xml" });
        articleService = (ArticleService) app.getBean("articleService");
    }
}

标签:java,spring,MongoDB

收藏

0人收藏

支持

0

反对

0

发表评论