关闭

使用spring连接及操作mongodb3.0

标签: mongodbspringjavaspring和java操作mongodb
24468人阅读 评论(12) 收藏 举报
分类:
前边有一篇记录过不使用spring,直接在java代码中连接和操作mongodb数据库,这里就紧随其后记录一下使用spring的情况下,在java中简单操作mongodb。

maven导包配置:
因为涉及了sping以及springmvc,因此也需要导入它们相关的包:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring_mongo</groupId>
  <artifactId>spring_mongo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring_mongo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.8.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.3</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.0.9.RELEASE</version>
    </dependency>
  </dependencies>
  <build>
  <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                    <compilerArguments>  
                      <verbose />  
                      <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>  
                    </compilerArguments>  
                </configuration>
            </plugin>
        </plugins>
    <finalName>spring_mongo</finalName>
  </build>
</project>



spring基础配置:
主要是开启注解扫描等:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"
    xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">

    <!-- 自动扫描(自动注入) -->
    <context:component-scan base-package="spring_mogo.dao.daoImp" />

    <!-- 导入mongodb的配置文件 -->
    <import resource="spring-mongodb305.xml" />

    <!-- 开启注解 -->
    <context:annotation-config />

</beans>


spring连接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:p="http://www.springframework.org/schema/p"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/data/mongo
            http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

    <!-- spring连接mongodb数据库的配置 -->
    <mongo:mongo-client host="192.168.0.201" port="27017" credentials="tuzongxun:123456@mongoTest" id="mongo">  
       <mongo:client-options write-concern="SAFE"/>  
    </mongo:mongo-client> 

    <mongo:db-factory  id="mongoDbFactory" dbname="mongoTest" mongo-ref="mongo" />  

    <!-- 只要使用这个调用相应的方法操作 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">  
       <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />  
    </bean>   

</beans>


与数据库对应的实体类:
需要注意的是这里需要实现序列化的接口并设置uid的属性,否则不能在操作中直接把数据库返回结果转换成对象属性:
package spring_mongo.models;

import java.io.Serializable;

public class UserModel implements Serializable {

    private static final long serialVersionUID = 1L;
    private String userName;
    private String password;

    public UserModel(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}


根据spring配置获取操作mongodb的MongoTemplete,需要实现ApplicationContextAware接口:
package spring_mogo.dao.daoImp;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.MongoTemplate;

public abstract class AbstractBaseMongoTemplete implements
        ApplicationContextAware {

    protected MongoTemplate mongoTemplate;

    /**
     * @Description 根据配置文件设置mongoTemplate
     * @param mongoTemplate
     */
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        MongoTemplate mongoTemplate = applicationContext.getBean(
                "mongoTemplate", MongoTemplate.class);
        setMongoTemplate(mongoTemplate);
    }
}



操作数据库的接口以及对应的实现类:
演示了最基础的增删改查,需要注意的地方在于参数的声明以及接收返回数据时和实体类的转换:
(1)接口:
package spring_mogo.dao;

import java.util.List;

import spring_mongo.models.UserModel;

public interface UserDao {
    /**
     * 查询数据
     * 
     * @author:tuzongxun
     * @Title: findAll
     * @param @return
     * @return List<UserModel>
     * @date May 13, 2016 3:07:39 PM
     * @throws
     */
    public List<UserModel> findAll();

    /**
     * 新增数据
     * 
     * @author:tuzongxun
     * @Title: insertUser
     * @param @param user
     * @return void
     * @date May 13, 2016 3:09:45 PM
     * @throws
     */
    public void insertUser(UserModel user);

    /**
     * 删除数据
     * 
     * @author:tuzongxun
     * @Title: removeUser
     * @param @param userName
     * @return void
     * @date May 13, 2016 3:09:55 PM
     * @throws
     */
    public void removeUser(String userName);

    /**
     * 修改数据
     * 
     * @author:tuzongxun
     * @Title: updateUser
     * @param @param user
     * @return void
     * @date May 13, 2016 3:10:06 PM
     * @throws
     */
    public void updateUser(UserModel user);

    /**
     * 按条件查询
     * 
     * @author:tuzongxun
     * @Title: findForRequery
     * @param
     * @return void
     * @date May 13, 2016 3:23:37 PM
     * @throws
     */
    public List<UserModel> findForRequery(String userName);

}


(2)实现类,这里要继承AbstractBaseMongoTemplete类,从而获得mongoTemplete进行各种操作:
package spring_mogo.dao.daoImp;

import java.util.List;

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.Component;

import spring_mogo.dao.UserDao;
import spring_mongo.models.UserModel;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Component("UserDaoImp")
public class UserDaoImp extends AbstractBaseMongoTemplete implements UserDao {

    /**
     * 查询所有数据
     * 
     * @author:tuzongxun
     * @Title: findAll
     * @Description: TODO
     * @param @return
     * @date May 13, 2016 3:10:29 PM
     * @throws
     */
    @Override
    public List<UserModel> findAll() {
        // 需要设置集合对应的尸体类和相应的集合名,从而查询结果直接映射
        List<UserModel> userList = mongoTemplate.findAll(UserModel.class,
                "user");
        return userList;
    }

    /**
     * 新增数据
     * 
     * @author:tuzongxun
     * @Title: insertUser
     * @Description: TODO
     * @param @param user
     * @date May 13, 2016 3:10:45 PM
     * @throws
     */
    @Override
    public void insertUser(UserModel user) {
        // 设置需要插入到数据库的文档对象
        DBObject object = new BasicDBObject();
        object.put("userName", user.getUserName());
        object.put("password", user.getPassword());
        mongoTemplate.insert(object, "user");
    }

    /**
     * 按条件删除数据
     * 
     * @author:tuzongxun
     * @Title: removeUser
     * @Description: TODO
     * @param @param userName
     * @date May 13, 2016 3:11:01 PM
     * @throws
     */
    @Override
    public void removeUser(String userName) {
        // 设置删除条件,如果条件内容为空则删除所有
        Query query = new Query();
        Criteria criteria = new Criteria("userName");
        criteria.is(userName);
        query.addCriteria(criteria);
        mongoTemplate.remove(query, "user");
    }

    /**
     * 修改数据
     * 
     * @author:tuzongxun
     * @Title: updateUser
     * @Description: TODO
     * @param @param user
     * @date May 13, 2016 3:11:12 PM
     * @throws
     */
    @Override
    public void updateUser(UserModel user) {
        // 设置修改条件
        Query query = new Query();
        Criteria criteria = new Criteria("userName");
        criteria.is(user.getUserName());
        query.addCriteria(criteria);
        // 设置修改内容
        Update update = Update.update("password", user.getPassword());
        // 参数:查询条件,更改结果,集合名
        mongoTemplate.updateFirst(query, update, "user");
    }

    /**
     * 根据条件查询
     * 
     * @author:tuzongxun
     * @Title: findForRequery
     * @Description: TODO
     * @param @param userName
     * @date May 13, 2016 4:08:15 PM
     * @throws
     */
    @Override
    public List<UserModel> findForRequery(String userName) {
        Query query = new Query();
        Criteria criteria = new Criteria("userName");
        criteria.is(userName);
        query.addCriteria(criteria);
        // 查询条件,集合对应的实体类,集合名
        List<UserModel> userList = mongoTemplate.find(query, UserModel.class,
                "user");
        return userList;
    }

}

测试类:
为了验证以上代码和配置的正确性,测试类代码如下:
package spring_mongo.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import spring_mogo.dao.UserDao;
import spring_mongo.models.UserModel;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml" })
public class mongoTest {

    @Autowired
    private UserDao userDao;

    /**
     * 查询测试
     * 
     * @author:tuzongxun
     * @Title: monFindTest
     * @param
     * @return void
     * @date May 13, 2016 3:27:51 PM
     * @throws
     */
    @Test
    public void monFindTest() {
        List<UserModel> userModels = userDao.findAll();
        if (userModels != null && userModels.size() > 0) {
            for (UserModel user : userModels) {
                System.out.println(user.getUserName() + ":"
                        + user.getPassword());
            }
        }
    }

    /**
     * 插入数据测试
     * 
     * @author:tuzongxun
     * @Title: monInsertTest
     * @param
     * @return void
     * @date May 13, 2016 3:27:38 PM
     * @throws
     */
    @Test
    public void monInsertTest() {
        UserModel user = new UserModel("test111", "123456");
        userDao.insertUser(user);
        this.monFindTest();
    }

    /**
     * 删除测试
     * 
     * @author:tuzongxun
     * @Title: monRemoveTest
     * @param
     * @return void
     * @date May 13, 2016 3:28:06 PM
     * @throws
     */
    @Test
    public void monRemoveTest() {
        String userName = "test111";
        userDao.removeUser(userName);
        this.monFindTest();
    }

    /**
     * 测试修改
     * 
     * @author:tuzongxun
     * @Title: monUpdateTest
     * @param
     * @return void
     * @date May 13, 2016 3:50:08 PM
     * @throws
     */
    @Test
    public void monUpdateTest() {
        UserModel user = new UserModel("test111", "test");
        userDao.updateUser(user);
        this.monFindTest();
    }

    /**
     * 按条件查询
     * 
     * @author:tuzongxun
     * @Title: monFindForRuq
     * @param
     * @return void
     * @date May 13, 2016 4:10:53 PM
     * @throws
     */
    @Test
    public void monFindForRuq() {
        String userName = "test111";
        List<UserModel> userModels = userDao.findForRequery(userName);
        if (userModels != null && userModels.size() > 0) {
            for (UserModel user : userModels) {
                System.out.println(user.getUserName() + ":"
                        + user.getPassword());
            }
        }
    }

}

后期补上demo下载地址:http://download.csdn.net/detail/tuzongxun/9710276

5
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

Mongo---配置多数据源

MongoDB需要配置多数据源 配置如下:spring-mongodb.xml为: <beans xmlns="http://www.springframework.org/schema/beans"...
  • q383965374
  • q383965374
  • 2017-08-14 15:37
  • 821

spring中配置mongoDB

spring中配置MongoDB有两种方式:注解方式和配置文件方式 1、注解方式 配置类要继承AbstractMongoConfiguration类,重写mongo()和mongoTemplate...
  • qq_21033663
  • qq_21033663
  • 2016-06-08 19:57
  • 6441

Spring整合Mongodb,Maven的依赖,Spring配置,MongoDB的公共操作类,使用SpringMVC的Controller进行测试并返回结果的案例

在和Spring和MongoDB进行整合的时候需要如下三个jar,分别是: spring-data-commons spring-data-mongodb mongo-java-driver ...
  • toto1297488504
  • toto1297488504
  • 2017-02-26 01:11
  • 1758

MongoDB整合Spring 详细讲解(含代码)

写这篇文章也做了下思考,首先是本人技术欠佳。但就是喜欢研究一些东西。因为在此之前有很多的朋友已经写过类似的,很多我也看过,但是讲解的不够深入。对有些朋友提出的问题不能给出答案。在这里,我根据我目前的能...
  • cuiran
  • cuiran
  • 2012-12-12 16:44
  • 107112

MongoDB学习笔记之 第4章 MongoDB整合Spring

MongoDB学习笔记之 第1章 MongoDB的安装 MongoDB学习笔记之 第2章 MongoDB的增删改查 MongoDB学习笔记之 第3章 MongoDB的Java驱动 MongoDB...
  • hxpjava1
  • hxpjava1
  • 2017-09-25 19:48
  • 339

spring配置mongodb

参考:http://blog.csdn.net/zhouzhiwengang/article/details/51446784 参考:http://blog.csdn.net/congcong68/a...
  • fuck487
  • fuck487
  • 2017-08-25 15:21
  • 231

mongoDB3.0x版本spring集成配置文件

spring连接mongodb以及建立相关工厂的配置: [html] view plain copy xml version="1.0" encoding="UTF-8"?> .....
  • yz7074998
  • yz7074998
  • 2017-06-11 19:44
  • 985

spring + mongodb 整合 Nosql mongodb 数据库配置文件

下图是Spring整合mongodb Nosql数据库的配置文件,具体配置楼主也不是很清楚,希望大神给与指点: <beans xmlns="http://www.springframework.o...
  • shasiqq
  • shasiqq
  • 2016-04-25 15:18
  • 1974

MongoDB的Spring配置使用

MongoDB的Spring配置使用 springboot学习笔记-3 整合redis&mongodb
  • u013467442
  • u013467442
  • 2017-03-20 22:34
  • 463

SpringMVC Mongodb 配置中加入用户认证信息

Spring Mongodb 配置中加入用户认证信息 Spring mongodb的项目搭建请参考:http://blog.csdn.net/h348592532/article/details/...
  • bruceoyqq
  • bruceoyqq
  • 2015-05-18 14:12
  • 5969
    有问题要问?点击QQ联系我!
    有需要,qq联系我
    1160569243
    公告栏
    个人资料
    • 访问:787103次
    • 积分:9966
    • 等级:
    • 排名:第2029名
    • 原创:229篇
    • 转载:38篇
    • 译文:0篇
    • 评论:408条