Spring整合MongoDB小Demo

Posted erkye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring整合MongoDB小Demo相关的知识,希望对你有一定的参考价值。

docker安装MongoDB

  • 查找mongoDB的镜像
docker search mongodb
  • 下载mongo镜像
docker pull mongo
  • 查看本地是否mongo的镜像
docker images
  • 运行容器,将端口映射到宿主机的27017端口
docker run -itd --name mongo -p 27017:27017 mongo

创建Maven工程(IDEA)

  • 添加依赖(Spring测试依赖、SpringData MongoDB依赖)
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-mongodb</artifactId>
      <version>1.10.6.RELEASE</version>
    </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
        <version>4.3.13.RELEASE</version>
        <exclusions>
          <exclusion>
            <artifactId>spring-core</artifactId>
            <groupId>org.springframework</groupId>
          </exclusion>
        </exclusions>
      </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  • resource目录下创建mongo.properties文件,存储连接的数据库和地址和端口
mongo.database=admin
mongo.server.address=127.0.0.1
mongo.server.port=27017
  • 创建com.test.config包,里面创建MongoConfig.java,使用@PropertySource注解读取刚才的配置文件,继承抽象类AbstractMongoConfiguration,重载getDatabaseName()和mongo()方法,注入Environment对象,使用配置文件中的配置
package com.test.config;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

/**
 * @author 11699
 * @date 20/3/21 - 11:11
 */
@Configuration
@PropertySource("classpath:mongo.properties")
public class MongoConfig extends AbstractMongoConfiguration {

    @Autowired
    private Environment env;

    @Override
    protected String getDatabaseName() {
        return env.getProperty("mongo.database");
    }

    @Override
    public Mongo mongo() throws Exception {
       return new MongoClient(
               env.getProperty("mongo.server.address"),
               Integer.parseInt(env.getProperty("mongo.server.port")));
    }
}
  • 创建con.test.domain包,创建Student类,使用@Document标记是这是一个文档,@Id标记id字段,@Field("stu_age")标记持久化时候对应的域名
package com.test.domain;

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

/**
 * @author 11699
 * @date 20/3/21 - 11:28
 */
@Document
public class Student {

    @Id
    private String id;

    private String name;

    @Field("stu_age")
    private Integer age;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  • 创建测试类 注入MongoOperations(MongoTemplate实现的接口)
package com.test;

import com.test.config.MongoConfig;
import com.test.domain.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Unit test for simple App.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfig.class)
public class AppTest {

    @Autowired
    private MongoOperations mongo;

}
  • 测试保存
@Test
public void testSave(){
    Student student = new Student();
    student.setName("小明");
    student.setAge(11);

    mongo.save(student, "stu");
}
  • 查询数量
@Test
public void testCount(){
    long count = mongo.getCollection("stu").count();
    System.out.println("数量为:"+ count);
}
  • 查询全部
@Test
public void testQuery(){
    List<Student> list = mongo.findAll(Student.class, "stu");
    for (Student student : list) {
        System.out.println(student);
    }
}
  • 根据id查询
@Test
public void testFindById(){
    Student stu = mongo.findById("5e759d94ecc4c0fe0007f312", Student.class, "stu");
    System.out.println(stu);
}
  • 复杂查询
@Test
public void testComplexQuery(){
    List<Student> list = mongo.find(Query.query(Criteria.where("name").is("小明")), Student.class, "stu");
    for (Student student : list) {
        System.out.println(student);
    }
}
  • 删除
@Test
public void testRemove(){
    //先查询
    Student stu = mongo.findById("5e759d94ecc4c0fe0007f312", Student.class, "stu");
    mongo.remove(stu);
}

源码下载

以上是关于Spring整合MongoDB小Demo的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合MongoDB教程

Spring整合Mybatis框架小demo

spring-boot整合mongodb多数据源的案例

SpringBoot整合MongoDB(实现一个简单缓存)

Dubbo Spring Boot 最佳实践整合 Demo 征集

spring小例子-springMVC+mybits整合的小例子