Spring Boot Rest Example With Mongodb

Creating Spring Boot Rest With Mongodb example application with simple steps.

Posted by dogukanhan on August 26, 2020 · 10 mins read

This writing shows how to create a restful web application with using spring and mongodb. I will show simple one controller and get, post http methods.

1-) go https://start.spring.io/ add Spring Web and Spring Data MongoDB( You may prefer to add more things but these are required.)

2-) Create application properties file in resources directory and append:

Change the mongodb connection with your connection details.

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

3-) Create Student entity 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
29
30
31
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 number, String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.number = number;
    }

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

}

4-) Create StudentRepository class so we can comminicate with the database.

1
2
3
4
5
import org.springframework.data.mongodb.repository.MongoRepository;

public interface StudentRepository extends MongoRepository<Student, String> {

}

5-) Create StudentService class, this class will be bridge between RestController class and Repository 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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
/*
   StudentService retries data from StudentResponse
 */
@Service
public class StudentService {

    private final StudentRepository studentRepository;

    public StudentService(@Autowired StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public List<Student> findAllStudents(){
        return studentRepository.findAll();
    }

    public void create(Student student){
        studentRepository.insert(student);
    }

}

6-) Create StudentDTO class, we will use this class to map our entity 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
29
30
31
32
33
34
public class StudentDTO {

    private String id;

    private String number;

    private String firstName;

    private String lastName;

    public StudentDTO(Student student){
        this.id = student.id;
        this.number = student.number;
        this.firstName = student.firstName;
        this.lastName = student.lastName;
    }

    public String getId() {
        return id;
    }

    public String getNumber() {
        return number;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

7-) Create StudentCreateDTO, this class will be used in POST request mapping.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class StudentCreateDTO {

    private String id;
    
    private String number;

    private String firstName;

    private String lastName;

    public StudentCreateDTO(Student student) {
        this.id = student.id;
        this.number = student.number;
        this.firstName = student.firstName;
        this.lastName =  student.lastName;
    }

    public StudentCreateDTO() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

8-) Finally Create StudentController class to retrive data from StudentService and send to client.

Use @Post mapping to handle Post requests. Map the StudentCreateDTO to Student and send it to StudentService to create new Student.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/*
    StudentController controls the action between
    StudentService and the client.
 */
@RequestMapping("/student")
@RestController
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List<StudentDTO> getAllStudents(){
        return studentService.findAllStudents().stream()
                .map(StudentDTO::new)
                .collect(Collectors.toList());
    }

    @PostMapping
    public StudentCreateDTO createStudent(StudentCreateDTO studentCreateDTO){
        Student student = new Student();
        student.number = studentCreateDTO.getNumber();
        student.firstName = studentCreateDTO.getFirstName();
        student.lastName = studentCreateDTO.getLastName();

        studentService.create(student);

        return new StudentCreateDTO(student);
    }

}