0Pricing
Spring Boot 4 Complete Guide · 课时

集成 NoSQL 数据库

学习如何使用 Spring Data 集成 NoSQL 数据库(如 MongoDB 或 Redis)并与其交互。

集成 NoSQL 数据库 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to NoSQL Databases

Traditional databases (like SQL) store data in structured tables. NoSQL databases offer a flexible alternative, ideal for handling large volumes of unstructured or semi-structured data.

  • Non-relational: No fixed schema.
  • Scalable: Easily scale horizontally.
  • Diverse Models: Document, Key-Value, Graph, Column-Family.

They are great for big data, real-time web apps, and microservices.

Spring Data's Role in NoSQL

Just like with JPA, Spring Data provides a consistent, familiar programming model for interacting with various NoSQL databases.

It simplifies data access by:

  • Reducing boilerplate code.
  • Offering repository interfaces.
  • Handling database-specific operations.

You get the Spring experience even with non-relational stores!

Our NoSQL Example: MongoDB

There are many NoSQL databases, like Redis (key-value), Cassandra (column-family), and Neo4j (graph). For this lesson, we'll focus on MongoDB, a popular document-oriented database.

In MongoDB, data is stored in flexible, JSON-like documents called BSON, grouped into collections.

Add MongoDB Dependency

First, we need to add the Spring Data MongoDB starter dependency to our project. This pulls in all necessary libraries to connect to MongoDB.

For Maven, add this to your pom.xml:

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

Configure MongoDB Connection

Next, tell Spring Boot how to connect to your MongoDB instance. You'll typically do this in your application.properties or application.yml file.

Here's a basic setup for a local MongoDB:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase

Define Your MongoDB Document

In MongoDB, data is stored in documents. We represent these documents in Java using simple POJOs (Plain Old Java Objects). Use Spring Data MongoDB annotations like @Document and @Id.

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

@Document(collection = "products")
public class Product {
  @Id
  private String id;
  private String name;
  private double price;

  public Product(String name, double price) {
    this.name = name;
    this.price = price;
  }

  // Getters and Setters (omitted for brevity)
  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 double getPrice() { return price; }
  public void setPrice(double price) { this.price = price; }

  @Override
  public String toString() {
    return "Product{id='" + id + "', name='" + name + "', price=" + price + '}';
  }
}

Create a MongoRepository

Spring Data MongoDB makes interacting with your documents easy through repository interfaces. Extend MongoRepository, specifying your document type and its ID type.

This gives you basic CRUD methods out-of-the-box!

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

@Repository
public interface ProductRepository extends MongoRepository<Product, String> {
  // Spring Data automatically generates methods based on method names
  Product findByName(String name);
}

Basic CRUD Operations

With MongoRepository, you can perform common operations:

  • Save: repository.save(product) to insert or update.
  • Find: repository.findById(id) to get a document by ID.
  • Find All: repository.findAll() to retrieve all documents.
  • Delete: repository.deleteById(id) to remove a document.

You can also define custom queries by simply declaring method names!

MongoDB Integration Demo

Let's put it all together! This Spring Boot application saves a product, finds it, and prints its details. Make sure MongoDB is running locally.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@SpringBootApplication
public class MongoDemoApplication {

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

  @Bean
  public CommandLineRunner demo(ProductRepository repository) {
    return (args) -> {
      System.out.println("--- MongoDB Demo ---");

      // Clear existing data (optional)
      repository.deleteAll();

      // Save a new product
      Product product1 = new Product("Laptop Pro", 1200.00);
      repository.save(product1);
      System.out.println("Saved: " + product1);

      // Find by name
      Product foundProduct = repository.findByName("Laptop Pro");
      System.out.println("Found by name: " + foundProduct);

      // Find all products
      System.out.println("All products:");
      repository.findAll().forEach(System.out::println);

      System.out.println("--- Demo End ---");
    };
  }

  // Nested Document class
  @Document(collection = "products")
  public static class Product {
    @Id
    private String id;
    private String name;
    private double price;

    public Product(String name, double price) {
      this.name = name;
      this.price = price;
    }

    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 double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() {
      return "Product{id='" + id + "', name='" + name + "', price=" + price + '}';
    }
  }

  // Nested Repository interface
  @Repository
  public interface ProductRepository extends MongoRepository<Product, String> {
    Product findByName(String name);
  }
}

Quick Check: NoSQL Repositories

You've seen how Spring Data simplifies NoSQL interactions. Which annotation marks a class as a MongoDB document in Spring Data?

Recap: NoSQL with Spring Data

Great job! You've learned how to integrate NoSQL databases using Spring Data. We covered:

  • The purpose of NoSQL databases.
  • Adding the MongoDB starter dependency.
  • Configuring connection properties.
  • Creating @Document classes and MongoRepository interfaces.
  • Performing basic CRUD operations.

Spring Data makes NoSQL as easy to use as traditional SQL databases!

常见问题解答

「集成 NoSQL 数据库」课时是免费的吗?

是的 — 「集成 NoSQL 数据库」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

「集成 NoSQL 数据库」这节课中我会学到什么?

学习如何使用 Spring Data 集成 NoSQL 数据库(如 MongoDB 或 Redis)并与其交互。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Complete Guide 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「集成 NoSQL 数据库」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?

能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 自定义 Spring Data 数据仓库
  2. 集成 NoSQL 数据库
  3. 使用 Spring Cache 进行缓存
  4. 使用 Flyway 进行数据库迁移
← 返回 Spring Boot 4 Complete Guide