Home  >  Article  >  Java  >  How to use SpringBoot MongoDB and MongoDB GridFS

How to use SpringBoot MongoDB and MongoDB GridFS

WBOY
WBOYforward
2023-05-14 09:37:13544browse

MongoDB的基本使用

添加依赖

	 
            org.springframework.boot
            spring-boot-starter-data-mongodb
        

配置application.yml

server:
  port: 8888
spring:
  application:
    name: dmeo-app
  data:
    mongodb:
      uri:  mongodb://root:123456@localhost:27017
      database: dmeo

配置启动类

@SpringBootApplication
@EntityScan("cn.ybzy.model")//扫描实体类
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application .class, args);
    }
}

配置日志

配置logback-spring.xml日志,非必要配置



    
    
    
    
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            utf8
        
    
    
    
        
            
            ${LOG_HOME}/xc.%d{yyyy-MM-dd}.log
        
        
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        
    
    
    
        
        0
        
        512
        
        
    
    
        
    
    
    
        
        
        
    

创建User文档对象

@Data
@ToString
@Document(collection = "user")
public class User {
    @Id
    private String uid;
    private String name;
    private Integer age;
    private String address;
}

创建UserRepository

创建UserRepository ,继承MongoRepository,并指定实体类型和主键类型

在MongoRepository中定义了很多现成的方法,可以更方便的使用。

Spring Data mongodb也提供了自定义方法的规则,按照findByXXX,findByXXXAndYYY、countByXXXAndYYY等规则定义方法,实现查询操作。

/**
 * @Author: CJ
 * @Description:
 **/
public interface UserRepository extends MongoRepository {
    /**
     * 根据页面名称查询
     * @param name
     * @return
     */
    User findByName(String name);
    /**
     * 根据页面名称和类型查询
     * @param name
     * @param age
     * @return
     */
    User findByNameAndAge(String name,Integer age);
    /**
     * 根据站点和页面类型查询记录数
     * @param name
     * @param age
     * @return
     */
    int countByNameAndAge(String name,Integer age);
    /**
     * 根据站点和页面类型分页查询
     * @param name
     * @param address
     * @param pageable
     * @return
     */
    Page findByNameAndAddress(String name, String address, Pageable pageable);
}

执行测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;
    @Test
    public void testFindAll() {
        //从0开始
        int page = 0;
        int size = 10;
        Pageable pageable = PageRequest.of(page, size);
        Page all = userRepository.findAll(pageable);
        System.out.println(all);
    }
    @Test
    public void testSave() {
        User user = new User();
        user.setName("lisi");
        user.setAddress("China");
        user.setAge(12);
        userRepository.save(user);
        System.out.println(user);
    }
    @Test
    public void testDelete() {
        userRepository.deleteById("5fce3a0728df2033145874fc");
    }
    @Test
    public void testUpdate() {
    	 /**
         * Optional是jdk1.8引入的类型,Optional是一个容器对象
         * 它包括了需要的对象,使用isPresent方法判断所包含对象是否为空
         * isPresent方法返回false则表示Optional包含对象为空,否则可以使用get()取出对象进行操作。
         * Optional的优点是:
         *      1、提醒非空判断。
         *      2、将对象非空检测标准化。
         */
        Optional optional = userRepository.findById("5fce3a0728df2033145874fc");
        if (optional.isPresent()) {
            User user = optional.get();
            user.setAge(22);
            userRepository.save(user);
        }
    }
    @Test
    public void testFindByName() {
        User user = userRepository.findByName("lisi");
        System.out.println(user);
    }
    @Test
    public void testCountByNameAndAge() {
        int count = userRepository.countByNameAndAge("lisi", 12);
        System.out.println(count);
    }
	//自定义条件查询
	@Test
    public void testExample() {
        //条件值
        User user= new User ();
        user.setAge(22);
        user.setAddress("China");
        //条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        //ExampleMatcher.GenericPropertyMatchers.contains() 包含关键字,即模糊查询
        exampleMatcher = exampleMatcher.withMatcher("address",
                ExampleMatcher.GenericPropertyMatchers.contains());
        //创建条件实例
        Example example = Example.of(user, exampleMatcher);
        //分页对象
        Pageable pageable = new PageRequest(0, 10);
        //分页查询
        Page UserList = cmsPageRepository.findAll(example, pageable);
        System.out.println(UserList);
    }
}

GridFS的基本使用

GridFS概述

GridFS是MongoDB提供的用于持久化存储文件的模块。

工作原理:

GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。

特点:

用于存储和恢复超过16M(BSON文件限制)的文件(如:图片、音频、视频等)

是文件存储的一种方式,但它是存储在MonoDB的集合中

可以更好的存储大于16M的文件

会将大文件对象分割成多个小的chunk(文件片段),一般为256k/个,每个chunk将作为MongoDB的一个文档(document)被存储在chunks集合中

用两个集合来存储一个文件:fs.files与fs.chunks

每个文件的实际内容被存在chunks(二进制数据)中,和文件有关的meta数据(filename,content_type,还有用户自定义的属性)将会被存在files集合中。

详细参考:官网文档

存放文件

How to use SpringBoot MongoDB and MongoDB GridFS

	@Autowired
    GridFsTemplate gridFsTemplate;
    @Test
    public void testSaveFile() throws FileNotFoundException {
        //要存储的文件
        File file = new File("C:\\Users\\JackChen\\Desktop\\360截图18141222225269.png");
        //定义输入流
        FileInputStream inputStram = new FileInputStream(file);
        //向GridFS存储文件
        ObjectId objectId =  gridFsTemplate.store(inputStram, "1.png", "");
        //得到文件ID
        String fileId = objectId.toString();
        //5fd46f5c3629763ad83f9b86
        System.out.println(fileId);
    }

文件存储成功得到一个文件id,该文件id是fs.files集合中的主键

How to use SpringBoot MongoDB and MongoDB GridFS

可以通过文件id查询fs.chunks表中的记录,得到文件的内容。

当GridFS中读取文件时,若文件分成多块,需要对文件的各分块进行组装、合并

How to use SpringBoot MongoDB and MongoDB GridFS

读取文件

定义一个Mongodb的配置类,初始化项目时创建一个GridFSBucket对象,用于打开下载流对象。

@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;
    }
}
    @Test
    public void testReadFile() throws IOException {
        //根据文件id查询文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5fd46f5c3629763ad83f9b86")));
        //打开一个下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建GridFsResource对象,获取流
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        File file = new File("C:\\Users\\JackChen\\Desktop\\2.png");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(gridFsResource.getInputStream(),fileOutputStream);
        fileOutputStream.close();
    }

How to use SpringBoot MongoDB and MongoDB GridFS

删除文件

	@Autowired
    GridFsTemplate gridFsTemplate;
    @Test
    public void testDelFile() throws IOException {
        //根据文件id删除fs.files和fs.chunks中的记录
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5fd46f5c3629763ad83f9b86")));
    }

How to use SpringBoot MongoDB and MongoDB GridFS

The above is the detailed content of How to use SpringBoot MongoDB and MongoDB GridFS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete