NoSQL 데이터베이스 통합
Spring Data를 사용해 MongoDB나 Redis 같은 NoSQL 데이터베이스를 통합하고 상호작용하는 방법을 배웁니다.
NoSQL 데이터베이스 통합은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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=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!
자주 묻는 질문
“NoSQL 데이터베이스 통합” 강의는 무료인가요?
네 — “NoSQL 데이터베이스 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“NoSQL 데이터베이스 통합”에서 뭘 배우나요?
Spring Data를 사용해 MongoDB나 Redis 같은 NoSQL 데이터베이스를 통합하고 상호작용하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“NoSQL 데이터베이스 통합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.