x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Spring Boot Mongodb example

    This tutorial shows how to configure and use Mongodb for CRUD operations in a Spring Boot application. We will use MongoTemplate to invoke CRUD operations on Mongodb on a User type object.

    Step 1) Add spring-boot-starter-data-mongodb dependency to pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    Step 2) Create User POJO class

    package com.example.demo;
    
    import java.util.Arrays;
    import org.springframework.data.annotation.Id;
    
    public class User {
    
        @Id
        private int id;
        private String email;
        private String[] addresses;
        
        public User() {}
        
        public User(int id, String email) {
         this.id = id;
         this.email = email;
        }
    
        //removed getter, setter for brevity
        
        @Override
        public String toString() {
            return "User [id=" + id + ", email=" + email + ", 
                addresses=" + Arrays.toString(addresses) + "]";
        }
    
        
    }        

    Step 3) Create UserRepository class

    UserRepository class contains CRUD operations that will be invoked on MongoDB. This will be injected with MongoTemplate by Spring framework which will connect to mongodb server at localhost:27017 and use test collection. You can change the configuration by creating MongoTemplate as a seperate bean.

             
    package com.example.demo;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.mongodb.core.MongoTemplate;
    
    import com.mongodb.ConnectionString;
    import com.mongodb.MongoClientSettings;
    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoClients;
    
    @Configuration
    public class MongoConfig {
    
        @Bean
        public MongoClient mongo() {
            ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
            MongoClientSettings mongoClientSettings 
                = MongoClientSettings.builder().applyConnectionString(
                    connectionString).build();
            return MongoClients.create(mongoClientSettings);
        }
    
        @Bean
        public MongoTemplate mongoTemplate() throws Exception {
            return new MongoTemplate(mongo(), "test");
        }
    
    } 

    package com.example.demo;
    
    import java.util.List;
    
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.stereotype.Component;
    
    import com.mongodb.client.result.UpdateResult;
    
    @Component
    public class UserRepository {
    
        private final MongoTemplate mongoTemplate;
    
        UserRepository(MongoTemplate mongoTemplate) {
            this.mongoTemplate = mongoTemplate;
        }
    
        public List<User> findAll() {
            return mongoTemplate.findAll(User.class);
        }
    
        public User findById(long id) {
            return mongoTemplate.findById(id, User.class);
        }
    
        public User save(User user) {
            mongoTemplate.save(user);
            return user;
        }
    
        public UpdateResult update(String[] addresses) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(1));
            Update update = new Update();
            update.set("addresses", addresses);
            //return mongoTemplate.updateFirst(query, update, User.class);
            return mongoTemplate.upsert(query, update, User.class);
    
        }
        
        public void deleteAll() {
            mongoTemplate.findAllAndRemove(new Query(), User.class);
        }
        
        public void delete(int id) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(1));
            mongoTemplate.remove(query, User.class);
        }
    }
                

    Step 4) Write UserApplication class

    UserApplication class calls CRUD operations on MongoDB for a User object using UserRepository

    package com.example.demo;
    
    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 UserApplication implements CommandLineRunner {
    
        @Autowired
        private UserRepository userRepository;
    
        public static void main(String[] args) {
            SpringApplication.run(UserApplication.class, args);
    
        }
    
        public void run(String... args) {
            String[] addresses = new String[] {"address1", "address2"};
            System.out.println("users in db " + userRepository.findAll());
            System.out.println("deleting all users in db ");
            userRepository.deleteAll();
            System.out.println("users in db " + userRepository.findAll());
            System.out.println("adding users in db ");
            userRepository.save(new User(1, "john@hotmail.com"));
            userRepository.save(new User(2, "mike@gmail.com"));
            System.out.println("users in db " + userRepository.findAll());
            System.out.println("looking for user with user id 1 in db");
            System.out.println(userRepository.findById(1));
            System.out.println("updating user in db ");
            userRepository.update(addresses);
            System.out.println(userRepository.findById(1));
        }
    }            

    Step 5) Run UserApplication

    Console Output :

    2021-08-18 15:43:52.576  INFO 816 --- [main] com.example.demo.UserApplication : Started UserApplication in 6.796 seconds (JVM running for 7.544)
    2021-08-18 15:43:52.808  INFO 816 --- [main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:14}] to localhost:27017
    users in db [User [id=1, email=john@hotmail.com, addresses=[address1, address2]], User [id=2, email=mike@gmail.com, addresses=null]]
    deleting all users in db 
    users in db []
    adding users in db 
    users in db [User [id=1, email=john@hotmail.com, addresses=null], User [id=2, email=mike@gmail.com, addresses=null]]
    looking for user with user id 1 in db
    User [id=1, email=john@hotmail.com, addresses=null]
    updating user in db 
    User [id=1, email=john@hotmail.com, addresses=[address1, address2]]   
    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This