Java Full Stack & Real Time Microserives Project @ 8 AM IST - Reach out in email for updates javaexpresschannel@gmail.com

Thursday, May 2, 2024

How to integrate mongodb in spring boot application

 To integrate MongoDB in a Spring Boot application, you need to follow these steps:

1. Add the Spring Boot Data MongoDB dependency to your `pom.xml` file.

2. Configure MongoDB connection properties in your `application.properties` or `application.yml` file.

3. Create a model class to represent the document structure in MongoDB.

4. Create a repository interface that extends `MongoRepository` to perform CRUD operations.

5. Use the repository in your service or controller classes.

Here's how you can do it:

1. Add the Spring Boot Data MongoDB dependency to your `pom.xml` file:

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

2. Configure MongoDB connection properties in your `application.properties` file:

spring.data.mongodb.uri=mongodb://localhost:27017/testdb

3. Create a model class to represent the document structure in MongoDB. For example, if you have a `User` document:

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.mapping.Document;


@Document(collection = "users")

public class User {

    @Id

    private String id;

    private String name;

    private String email;

}

4. Create a repository interface that extends `MongoRepository` to perform CRUD operations:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserRepository extends MongoRepository<User, String> {

}

5. Use the repository in your service or controller classes:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


@Service

public class UserService {

    @Autowired

    private final UserRepository userRepository;

    public User saveUser(User user) {

        return userRepository.save(user);

    }

}

Remember to replace `localhost:27017/testdb` with your actual MongoDB connection string and `User` with your actual document structure.

0 comments:

Post a Comment