1 Star 0 Fork 57

ovoMing / blog

forked from turnon / blog 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
22.Spring访问MongoDB.md 6.51 KB
一键复制 编辑 原始数据 按行查看 历史
turnon 提交于 2023-02-10 11:40 . docs: 更新文档
title: Spring 访问 MongoDB
date: 2018-12-15 17:29:36
categories:
  - Java
  - 框架
  - Spring
  - Spring数据
tags:
  - Java
  - 框架
  - Spring
  - SpringBoot
  - MongoDB
permalink: /pages/db2a41/

Spring 访问 MongoDB

简介

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

在 Spring 中,spring-data-mongodb 项目对访问 MongoDB 进行了 API 封装,提供了便捷的访问方式。 Spring Data MongoDB 的核心是一个以 POJO 为中心的模型,用于与 MongoDB DBCollection 交互并轻松编写 Repository 样式的数据访问层。

spring-boot 项目中的子模块 spring-boot-starter-data-mongodb 基于 spring-data-mongodb 项目,做了二次封装,大大简化了 MongoDB 的相关配置。

Spring Boot 快速入门

引入依赖

在 pom.xml 中引入依赖:

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

数据源配置

spring.data.mongodb.host = localhost
spring.data.mongodb.port = 27017
spring.data.mongodb.database = test
spring.data.mongodb.username = root
spring.data.mongodb.password = root

定义实体

定义一个具有三个属性的 Customer 类:idfirstNamelastName

import org.springframework.data.annotation.Id;

public class Customer {

    @Id
    public String id;

    public String firstName;

    public String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
            "Customer[id=%s, firstName='%s', lastName='%s']",
            id, firstName, lastName);
    }

}

spring-data-mongodb 会将 Customer 类映射到一个名为 customer 的集合中。如果要更改集合的名称,可以在类上使用 @Document 注解。

创建 Repository

spring-data-mongodb 继承了 Spring Data Commons 项目的能力,所以可以使用其通用 API——Repository

先定义一个 CustomerRepository 类,继承 MongoRepository 接口,并指定其泛型参数:CustomerString。MongoRepository 接口支持多种操作,包括 CRUD 和分页查询。在下面的例子中,定义了两个查询方法:

import java.util.List;

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

public interface CustomerRepository extends MongoRepository<Customer, String> {

    Customer findByFirstName(String firstName);
    List<Customer> findByLastName(String lastName);

}

创建 Application

创建一个 Spring Boot 的启动类 Application,并在启动的 main 方法中使用 CustomerRepository 实例访问 MongoDB。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DataMongodbApplication implements CommandLineRunner {

    @Autowired
    private CustomerRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(DataMongodbApplication.class, args);
    }

    @Override
    public void run(String... args) {

        repository.deleteAll();

        // save a couple of customers
        repository.save(new Customer("Alice", "Smith"));
        repository.save(new Customer("Bob", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName('Alice'):");
        System.out.println("--------------------------------");
        System.out.println(repository.findByFirstName("Alice"));

        System.out.println("Customers found with findByLastName('Smith'):");
        System.out.println("--------------------------------");
        for (Customer customer : repository.findByLastName("Smith")) {
            System.out.println(customer);
        }
    }

}

运行 DataMongodbApplication 的 main 方法后,输出类似如下类容:

Customers found with findAll():
-------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith)

Customer found with findByFirstName('Alice'):
--------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customers found with findByLastName('Smith'):
--------------------------------
Customer(id=63d6157b265e7c5e48077f63, firstName=Alice, lastName=Smith)
Customer(id=63d6157b265e7c5e48077f64, firstName=Bob, lastName=Smith)

示例源码

更多 Spring 访问 MongoDB 示例请参考:MongoDB 示例源码

参考资料

JavaScript
1
https://gitee.com/ovoMing/blog.git
git@gitee.com:ovoMing/blog.git
ovoMing
blog
blog
master

搜索帮助