springboot-SpringBoot 2 and mongodb CRUD example

1. Introduction

This article would demo how to use SpringBoot 2 to do simple CRUD(create-read-update-delete) operations on MongoDB.

2. Environments

  • SpringBoot 2.x
  • MongoDB
  • jdk 1.8

3. The example

3.1 Define dependency in your pom

Add spring data mongodb to your pom like this:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.0.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

3.2 Define your domain class

Let’s define a domain class that would map to MongoDB document like this:

@Document(collection = "customers")
public class Customer {
    @Id
    private Long id;

    @Indexed(unique = true)
    private String code;// the code should be unique for every customer

    private String firstName;
    private String lastName;
    private int age;

    public Customer() {}

    public Customer(Long id,String code,String firstName, String lastName) {
        this.id = id;
        this.code = code;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", code='" + code + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                '}';
    }
    //getters and setters
}

It’s very simple:

  • the @Id indicates that the id is the MongoDB’s primary key
  • the @Indexed means the code column would be indexed and keep unique

3.3 Define your MongoRepository

We should define a custom class which extends the MongoRepository to get the abilities of spring data mongodb.

public interface CustomerRepository extends MongoRepository<Customer, Long> {
    Customer findByCode(String code);
    List<Customer> findByLastName(String lastName);
}

The MongoRepository<Customer, Long> means:

  • Our MongoDB document class is an instance of Customer
  • Our MongoDB document id is an instance of Long

The parent class MongoRepository has many good features that you can use:

image desc

3.4 Configure by application.properties

#mongodb
spring.data.mongodb.host=1.1.1.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=TEST_DB

#logging
logging.level.org.springframework.data=debug
logging.level.=error

3.5 Write a CommandLineRunner to test your code

@Component
public class MyMongoCommand implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyMongoCommand.class);

    @Autowired
    private CustomerRepository repository;

    @Override
    public void run(String... strings) throws Exception {
        repository.deleteAll();

        // save a couple of customers
        repository.save(new Customer(1l,"001","Alice", "Smith"));
        repository.save(new Customer(2l,"002","Bob", "Smith"));

        // fetch all customers
        logger.info("Customers found with findAll():");
        logger.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            logger.info(customer.toString());
        }
        logger.info("");

        // fetch and update an individual customer
        logger.info("Customer found with findByCode('001'):");
        logger.info("--------------------------------");
        Customer theCustomer = repository.findByCode("001");
        logger.info(theCustomer.toString());
        theCustomer.setAge(12);
        repository.save(theCustomer);
        Customer theCustomer2 = repository.findByCode("001");
        logger.info("updated customer:"+theCustomer2.toString());
        logger.info("");

        logger.info("Customers found with findByLastName('Smith'):");
        logger.info("--------------------------------");
        for (Customer customer : repository.findByLastName("Smith")) {
            logger.info(customer.toString());
        }
    }
}

Run the SpringBoot app and we would get this result: image desc

4. Summary

You can see that spring data mongodb make the mongodb operations more simpler.