SpringBoot actual combat (18) | integration MongoDB

  java, java-web, mongodb, springboot

WeChat Public Number: An Outstanding Disabled Person. If you have any questions, please leave a message backstage. I won’t listen anyway.

广东清远

Preface

For example, today I will introduce how SpringBoot integrates MongoDB.

Introduction to MongoDB

MongoDB is a non-relational database written by C++. It is an open source database system based on distributed file storage. It stores data as a document and its data structure consists of key=>value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays and document arrays, which is very flexible. The storage structure is as follows:

{
    "studentId": "201311611405",
    "age":24,
    "gender":"男",
    "name":"一个优秀的废人"
}

Preparatory work

  • SpringBoot 2.1.3 RELEASE
  • MongnDB 2.1.3 RELEASE
  • MongoDB 4.0
  • IDEA
  • JDK8
  • Create a database named test, which will not be built. Refer to the novice tutorial:

http://www.runoob.com/mongodb …

Configure data sources

spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/test

The above is written without a password. If MongoDB sets a password, it should be set as follows:

spring:
  data:
    mongodb:
      uri: mongodb://name:password@localhost:27017/test

Pom dependent configuration

<!-- mongodb 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- web 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok 依赖 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!-- test 依赖(没用到) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Entity class

@Data
public class Student {

    @Id
    private String id;

    @NotNull
    private String studentId;

    private Integer age;

    private String name;

    private String gender;

}

Dao layer

Like JPA, SpringBoot has also prepared a Repository for developers. It only needs to inherit the entity type and primary key type passed in by MongoRepository.

@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}

Service layer

public interface StudentService {

    Student addStudent(Student student);

    void deleteStudent(String id);

    Student updateStudent(Student student);

    Student findStudentById(String id);

    List<Student> findAllStudent();

}

Implementation class:

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 添加学生信息
     * @param student
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Student addStudent(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 根据 id 删除学生信息
     * @param id
     */
    @Override
    public void deleteStudent(String id) {
        studentRepository.deleteById(id);
    }

    /**
     * 更新学生信息
     * @param student
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Student updateStudent(Student student) {
        Student oldStudent = this.findStudentById(student.getId());
        if (oldStudent != null){
            oldStudent.setStudentId(student.getStudentId());
            oldStudent.setAge(student.getAge());
            oldStudent.setName(student.getName());
            oldStudent.setGender(student.getGender());
            return studentRepository.save(oldStudent);
        } else {
            return null;
        }
    }

    /**
     * 根据 id 查询学生信息
     * @param id
     * @return
     */
    @Override
    public Student findStudentById(String id) {
        return studentRepository.findById(id).get();
    }

    /**
     * 查询学生信息列表
     * @return
     */
    @Override
    public List<Student> findAllStudent() {
        return studentRepository.findAll();
    }
}

Controller layer

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @PostMapping("/add")
    public Student addStudent(@RequestBody Student student){
        return studentService.addStudent(student);
    }

    @PutMapping("/update")
    public Student updateStudent(@RequestBody Student student){
        return studentService.updateStudent(student);
    }

    @GetMapping("/{id}")
    public Student findStudentById(@PathVariable("id") String id){
        return studentService.findStudentById(id);
    }

    @DeleteMapping("/{id}")
    public void deleteStudentById(@PathVariable("id") String id){
        studentService.deleteStudent(id);
    }

    @GetMapping("/list")
    public List<Student> findAllStudent(){
        return studentService.findAllStudent();
    }

}

test result

MongoDB 增删改查

Postman tests have all passed, and only the save operation is shown here.

数据库结果

A database visualization tool Robo 3T is recommended here. Download address:https://robomongo.org/download

Complete code

https://github.com/turoDog/De …

If you think it is helpful to you, please give a Star before you leave. thank you very much.

Postscript

If this article is of any help to you, please help me look good. Your good looks are my motivation to persist in writing.

In addition, after the attention is sent1024Free study materials are available.

For details, please refer to this old article:Python, C++, Java, Linux, Go, Front End, Algorithm Data Sharing

一个优秀的废人,给你讲几斤技术