0Pricing
Spring Boot 4 Complete Guide · レッスン

NoSQLデータベースの統合

Spring Dataを使用して、MongoDBやRedisなどのNoSQLデータベースを統合し、操作する方法を学習します。

「NoSQLデータベースの統合」はCoddyKit上の無料Spring Boot 4 Complete Guideレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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データベースの統合」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Complete Guideコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。

「NoSQLデータベースの統合」で何を学びますか?

Spring Dataを使用して、MongoDBやRedisなどのNoSQLデータベースを統合し、操作する方法を学習します。 ブラウザで直接実行するハンズオンコードでSpring Boot 4 Complete Guideを演習し、24時間対応の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に戻る