Spring Boot Mongodb Example

Creating Spring boot mongodb example application with simple steps.

Posted by dogukanhan on August 25, 2020 · 3 mins read

In this turtorial, I will show how to create a spring boot application with mongodb connection. It’s very basic and easy with using spring initializr.

1-) Go https://start.spring.io/ and create a spring boot application that has Spring Data MongoDB extension.

2-) Download the generated starter project, unzip it and open with your IDE.

3-) Go src/main/resources/application.properties file.

1
2
3
4
5
6
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=test
spring.data.mongodb.username=mongoadmin
spring.data.mongodb.password=secret

Add this code to the file and change connection information by your connection details.

4-) Create a Student.java class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import org.springframework.data.annotation.Id;

public class Student {

    @Id
    public String id;
    
    public String number;

    public String firstName;
    
    public String lastName;

    public Student() {}

    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Student[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }
    
}

5-) Create StudentRepository.java class

1
2
3
4
public interface StudentRepository extends MongoRepository<Student, String> {

}

6-) Extend CommandLineRunner in Application class and override run method. Inject repository with @Autowired annotation. You can do your logic in the run method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootApplication
public class MongodbtestApplication implements CommandLineRunner {

    @Autowired
    private StudentRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(MongodbtestApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
		repository.save(new Student("111", "Alice", "Smith"));
    }
}