springboot集成mongdb 操作数据及文件存储下载

本文档详细介绍了如何在Windows上快速下载并安装MongoDB,以及如何配置数据库路径。接着,展示了如何在SpringBoot项目中集成MongoDB,包括在pom.xml中添加依赖,配置application.properties文件,创建配置类MongoConfig,定义实体类Employee,实现DAO层接口,并进行单元测试,包括数据的增删查改及文件上传下载操作。
摘要由CSDN通过智能技术生成

一、安装

如果去官网下载mongdb的话比较麻烦,http://www.mongodb.org。建议去http://dl.mongodb.org/dl/win32/x86_64这个地址下载,方便快捷

安装好之后,去安装目录启动,我安装到了C盘C:\Program Files\MongoDB\Server\4.0\bin。cd进入该目录,然后命令启动:mongod --dbpath E:\mongdb\data  如图:

 访问:http://localhost:27017/

说明启动成功

二、代码集成 

1、pom.xml

版本需要对应,我这里是springboot2.0.4.RELEASE对应mongdb4.0

<?xml version="1.0" encoding="UTF-8"?>

<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>

	 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
	
  <groupId>com.zhouzy.springboot</groupId>
  <artifactId>zhouzy-mongdb</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>zhouzy-springboot</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>


  <dependencies>
      	<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      	</dependency>
      	<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
      	<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.28</version>
		</dependency>
        
        <dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <scope>provided</scope>
		</dependency>
  	
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    	 <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
  </build>
</project>

2、application.properties

配置数据源

spring.data.mongodb.uri=mongodb://zhouzy:123456@localhost:27017/zhouzy
spring.data.mongodb.database=zhouzy

3、配置类

package com.zhouzy.springboot.config;

/**
 * @author john
 * @date 2019/12/21 - 10:39
 */


import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.database}")
    String db;

    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }
}

4、实体类

package com.zhouzy.springboot.model;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;

/**
 * @author zhouzhiyao
 * @date 20210711
 */
public class Employee {
	 	@Id
	    private ObjectId id;
	    private String name;
	    private Integer age;
		public ObjectId getId() {
			return id;
		}
		public void setId(ObjectId 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;
		}
	    
	    
}

5、dao层

package com.zhouzy.springboot.dao;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.zhouzy.springboot.model.Employee;

/**
 * @author zhouzhiyao
 * @date 20210711
 */
public interface EmpRepository extends MongoRepository<Employee, Long> {
    Employee findByName(String name);
    List<Employee> findByAgeGreaterThan(int age);
}

6、单元测试

包含了各种查询,保存以及文件上传下载

package com.zhouzy.springboot.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.zhouzy.springboot.dao.EmpRepository;
import com.zhouzy.springboot.model.Employee;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongdbTest {
	@Autowired
    private EmpRepository empRepository;

    @Autowired
    private MongoTemplate mongoTemplate;
    
    // 获得SpringBoot提供的mongodb的GridFS对象
    @Autowired
    private GridFsTemplate gridFsTemplate;
    
    @Autowired
    GridFSBucket gridFSBucket;
    
    @Test
    public void testSave() {
        Employee employee = new Employee();
        employee.setName("周先生");
        employee.setAge(33);
        empRepository.save(employee);
        System.out.println(employee);
    }

    @Test
    public void testQuery() {
        Employee employee = empRepository.findByName("周先生");
        System.out.println(employee);
    }

    @Test
    public void testOtherQuery() {
                // 通过MongoTemplate来查询数据
        Query query = new Query(Criteria.where("age").in(18, 35));
        List<Employee> employees = mongoTemplate.find(query, Employee.class);
        System.out.println(employees);
    }

    @Test
    public void testWhereQuery() {
        // 查询年龄大于30的数据
        List<Employee> employeeList = empRepository.findByAgeGreaterThan(30);
        System.out.println(employeeList);
    }
    
    @Test
    public void testUploadFile(){
         // 获得文件输入流
         InputStream ins;
		try {
			ins = new FileInputStream("E:\\https.docx");
			 // 获得文件类型
	         String contentType = "docx";
	         // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
	         ObjectId gridFSFile = gridFsTemplate.store(ins, "https", contentType);
	         
	         
	         
	         Query query = Query.query(Criteria.where("_id").is(gridFSFile.toString()));
	         // 查询单个文件
	         GridFSFile gfsfile = gridFsTemplate.findOne(query);
	         if (gfsfile == null) {
	             return;
	         }
	         //打开下载流对象
	         GridFSDownloadStream gridFSDownloadStream =
	                 gridFSBucket.openDownloadStream(gfsfile.getObjectId());
	         
	         //创建gridFsResource,用于获取流对象
	         GridFsResource gridFsResource = new GridFsResource(gfsfile, gridFSDownloadStream);
	         //获取流中的数据
	         InputStream inputStream = gridFsResource.getInputStream();
	         File f1 = new File("E:\\https2.docx");
	         if (!f1.exists()) {
	             f1.getParentFile().mkdirs();
	         }
	         byte[] bytes = new byte[1024];
	         // 创建基于文件的输出流
	         FileOutputStream fos = new FileOutputStream(f1);
	         int len = 0;
	         while ((len = inputStream.read(bytes)) != -1) {
	             fos.write(bytes, 0, len);
	         }
	         inputStream.close();
	         fos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
         
    }

}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wwwzhouzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值