Spring Boot 4 Complete Guide · Leçon

Intégration de bases de données NoSQL

Apprenez à intégrer des bases de données NoSQL telles que MongoDB ou Redis avec Spring Data et à interagir avec elles.

Leçon 2 sur 411 étapes

Intégration de bases de données NoSQL est une leçon Spring Boot 4 Complete Guide gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Complete Guide, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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!

Gratuit pour commencer

Apprends Java avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
21
Leçons
84

Questions Fréquemment Posées

La leçon « Intégration de bases de données NoSQL » est-elle gratuite ?

Oui — le texte complet de « Intégration de bases de données NoSQL » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Complete Guide, passe à CoddyKit PRO. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Intégration de bases de données NoSQL » ?

Apprenez à intégrer des bases de données NoSQL telles que MongoDB ou Redis avec Spring Data et à interagir avec elles. Tu pratiques Spring Boot 4 Complete Guide avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Spring Boot 4 Complete Guide ?

Aucune expérience préalable n'est requise. Spring Boot 4 Complete Guide sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Intégration de bases de données NoSQL » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Complete Guide ?

Oui. Chaque leçon Spring Boot 4 Complete Guide inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Référentiels Spring Data personnalisés
  2. Intégration de bases de données NoSQL
  3. Mise en cache avec Spring Cache
  4. Migrations de bases de données avec Flyway
← Retour à Spring Boot 4 Complete Guide