Integration von NoSQL-Datenbanken
Lernen Sie, NoSQL-Datenbanken wie MongoDB oder Redis mit Spring Data zu integrieren und zu verwenden.
Integration von NoSQL-Datenbanken ist eine kostenlose Spring Boot 4 Complete Guide-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Boot 4 Complete Guide-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Boot 4 Complete Guide-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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=mydatabaseDefine 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
@Documentclasses andMongoRepositoryinterfaces. - Performing basic CRUD operations.
Spring Data makes NoSQL as easy to use as traditional SQL databases!
Häufig gestellte Fragen
Ist die Lektion „Integration von NoSQL-Datenbanken“ kostenlos?
Ja — der vollständige Text von „Integration von NoSQL-Datenbanken“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Boot 4 Complete Guide-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Boot 4 Complete Guide-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Integration von NoSQL-Datenbanken“?
Lernen Sie, NoSQL-Datenbanken wie MongoDB oder Redis mit Spring Data zu integrieren und zu verwenden. Du übst Spring Boot 4 Complete Guide mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Boot 4 Complete Guide zu starten?
Keine Vorkenntnisse erforderlich. Spring Boot 4 Complete Guide auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Integration von NoSQL-Datenbanken“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Boot 4 Complete Guide-Lektion Code schreiben und ausführen?
Ja. Jede Spring Boot 4 Complete Guide-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Benutzerdefinierte Spring-Data-Repositories
- Integration von NoSQL-Datenbanken
- Caching mit Spring Cache
- Datenbankmigrationen mit Flyway