springboot 访问mongodb 25

2020-04-15  本文已影响0人  张力的程序园

1、环境约束

2、前提约束

3、操作步骤

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.4.3</version>
        </dependency>
server.port=9999
spring.data.mongodb.uri=mongodb://localhost:27017
spring.data.mongodb.database=ali
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//相当于xml
public class MongoConfig {
    @Value("${spring.data.mongodb.database}")//直接引用的是application.properties中的key
    String db;
    @Bean//bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }
}

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;

@RestController
public class MongoController {

    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    @Resource
    StudentDao studentDao;

    @RequestMapping("/gridfs/add")
    @ResponseBody
    public String addFile() throws FileNotFoundException {
        //要存储的文件
        File file = new File("D:\\1001.html");//假设存在该文件
        //定义输入流
        FileInputStream inputStram = new FileInputStream(file);
        //向GridFS存储文件
        ObjectId objectId = gridFsTemplate.store(inputStram, "1001", "text");
        //得到文件ID
        String fileId = objectId.toString();
        return fileId;
    }

    @RequestMapping("/gridfs/fetch")
    @ResponseBody
    public String fetch() throws IOException {
        String fileId = "5e967f8c3930f45a6c2a8e85";//假设fs.files中有这样一个文件
        //根据id查询文件
        GridFSFile gridFSFile =
                gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream =
                gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource,用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        //获取流中的数据
        String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");

        return "ok";
    }

    @RequestMapping("/gridfs/download")
    @ResponseBody
    public String download() throws IOException {

        // 获取文件ID
        String objectId = "5e4f36ec3930f41b4456a7af";
        // 获取文件流,定义存放位置和名称
        File file = new File("D:/1001.html");
        // 创建输出流
        OutputStream os = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(new ObjectId(objectId), os);
        return "ok";
    }

    @RequestMapping("/gridfs/delete")
    @ResponseBody
    public String testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
        return "ok";
    }


    @RequestMapping("/mongo/insert")
    @ResponseBody
    public String insert(Student student) {
        studentDao.save(student);
        return "ok";
    }

    @RequestMapping("/mongo/list")
    @ResponseBody
    public Page<Student> list() {
        Pageable pageable = PageRequest.of(1, 2);
        Page<Student> page = studentDao.findAll(pageable);
        return page;
    }

    @RequestMapping("/mongo/get/{name}")
    @ResponseBody
    public Page<Student> getStudentsByName(@PathVariable("name") String name) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("name",
                ExampleMatcher.GenericPropertyMatchers.contains()).withIgnorePaths("_class");
        Student info = new Student();
        info.setName(name);
        Example<Student> example = Example.of(info, exampleMatcher);
        Pageable pageable = PageRequest.of(0, 4);
        Page<Student> page = studentDao.findAll(example, pageable);
        return page;
    }
}
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentDao extends MongoRepository<Student,String> {
}
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;

@Document(collection = "student")
public class Student implements Serializable {

    private String _id;
    private String name;
    private String age;

    public Student() {
    }

    public Student(String _id, String name, String age) {

        this._id = _id;
        this.name = name;
        this.age = age;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

以上就是springboot中对mongodb普通数据和文件的操作。

上一篇下一篇

猜你喜欢

热点阅读