Java > Spring Framework > Spring Data > Spring Data MongoDB
Defining a MongoDB Repository with Spring Data
This snippet demonstrates how to define a simple repository interface using Spring Data MongoDB. This interface allows you to interact with a MongoDB collection without writing boilerplate code for common database operations.
Project Setup (pom.xml)
This configuration adds the necessary dependencies for Spring Boot and Spring Data MongoDB to your project. Specifically, spring-boot-starter-data-mongodb
includes dependencies for MongoDB driver, Spring Data Commons, Spring Data MongoDB, and Spring beans for connecting to MongoDB.
<!-- Maven dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Define a Model (Entity)
This class represents a Product
entity that will be stored in MongoDB. The @Document
annotation specifies the collection name (products
). The @Id
annotation marks the id
field as the primary key.
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() {}
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;
}
}
Create a Repository Interface
This interface extends MongoRepository
, providing basic CRUD operations for the Product
entity, using String
as the type for the ID. No further implementation is needed; Spring Data MongoDB will automatically generate the necessary code.
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ProductRepository extends MongoRepository<Product, String> {
// Custom query methods can be defined here
}
Using the Repository
This code demonstrates how to use the ProductRepository
to save a new Product
and retrieve all products. The @Autowired
annotation injects the ProductRepository
instance. The run
method executes after the application context is loaded.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private ProductRepository productRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// Create a new product
Product product = new Product("Laptop", 1200.00);
productRepository.save(product);
// Find all products
productRepository.findAll().forEach(System.out::println);
}
}
Concepts Behind the Snippet
This snippet showcases the power of Spring Data MongoDB's repository abstraction. By extending MongoRepository
, you inherit a set of pre-built methods for common database operations, reducing the amount of boilerplate code you need to write. This improves development speed and maintainability.
Real-Life Use Case
Imagine an e-commerce application where you need to manage products. You can use Spring Data MongoDB to create repositories for products, customers, orders, and other entities, enabling efficient data access and manipulation.
Best Practices
Interview Tip
Be prepared to explain the benefits of using Spring Data MongoDB, such as reduced boilerplate code, improved maintainability, and seamless integration with Spring's dependency injection and transaction management features.
When to use them
Use Spring Data MongoDB when you need to interact with a MongoDB database in a Spring application. It's particularly useful for projects that require a flexible and scalable data store.
Memory footprint
Spring Data MongoDB's memory footprint is relatively small. The library itself doesn't consume a significant amount of memory. The main memory usage comes from the MongoDB driver and the data stored in the database.
Alternatives
Pros
Cons
FAQ
-
What is Spring Data MongoDB?
Spring Data MongoDB is a Spring module that provides an abstraction layer for interacting with MongoDB databases. It simplifies data access and reduces the amount of boilerplate code you need to write. -
How do I define custom queries in a Spring Data MongoDB repository?
You can define custom queries by declaring methods in your repository interface with specific naming conventions or by using the@Query
annotation. -
How do I configure the MongoDB connection?
You can configure the MongoDB connection by providing the necessary properties in yourapplication.properties
orapplication.yml
file, such asspring.data.mongodb.uri
,spring.data.mongodb.database
, andspring.data.mongodb.port
.