Use springboot to connect to mongodb database and operate

This article mainly guides to build a demo that integrates swaggerUI with springboot and operates the mongodb database in the simplest way.The nonsense is not right, go directly to the process:

1. Create a springboot project

Insert picture description here
Insert picture description hereInsert picture description here

2. Add swagger's pom dependency

Add the jar package to be imported into the pom file:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<!-- 接口API生成html文档 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

3. Add connection configuration item of mongodb database

Add the configured ip, port number and database name directly to the application.properties file, add the account password, and configure it to yml can modify the file by itself

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=Test

4. Create a package structure

Insert picture description here

5. Write code

  • Swagger startup class:
package com.mongodb.demo.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2).select().
        	apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    }
}

Use @Configuration to mark this as a startup class that needs to be loaded by spring. Use @ EnableSwagger2 to indicate that this is the startup class of swagger

  • user entity class
package com.mongodb.demo.entity;

/**
 * <p>title:com.mongodb.demo.entity</p>
 * <p>Company:阿里巴巴</p>
 * author:及时雨
 * date:2019/9/1
 * version 1.0
 */

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * 实体层
 * @author linhongcun
 *
 */
@Document(collection="t_user")
public class User {

    @Id // 指定ID
    private String id;

    @Field("userName") // 指定域名,覆盖默认
    private String userName;

    @Field("password") // 指定域名,覆盖默认
    private String password;

    public String getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}


@Document (collection = “t_user”) The table name is a document object, t_user is the collection you need to insert (similar to the table name), @Id is id, it will be created automatically if you do n’t write, @Field is the key of the key-value pair value

  • The controller class, which originally needed to be written in layers, is written directly for simplicity here.
package com.mongodb.demo.controller;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mongodb.demo.entity.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 控制层
 * @author linhongcun
 *
 */
@RestController
@RequestMapping("/user")
@EnableSwagger2
public class UserController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 1、增
     * @param user
     * @return
     */
    @PostMapping("/insert")
    @ApiOperation (value = "insert",notes = "插入")
    public User insertUser(User user) {
        // 可以用 save 替代
        mongoTemplate.insert(user);
        return user;
    }

    /**
     * 2、查
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    @ApiOperation (value = "get",notes = "查询")
    public User getUserById(@PathVariable String id) {
        return mongoTemplate.findById(id, User.class);
    }

    /**
     * 3、删
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation (value = "delete",notes = "删除")
    public User deleteUserById(@PathVariable String id) {
        User user = mongoTemplate.findById(id, User.class);
        mongoTemplate.remove(user);
        return user;
    }

    /**
     * 4、改
     * @param user
     * @return
     */
    @PutMapping("/update")
    @ApiOperation (value = "update",notes = "修改")
    public User updateUser(User user) {
        // save 可增可改!
        mongoTemplate.save(user);
        return user;
    }

    /**
     * 5、全
     * @return
     */
    @GetMapping("/get/all")
    @ApiOperation (value = "getAll",notes = "获取所有")
    public List<User> getAllUsers() {
        return mongoTemplate.findAll(User.class);
    }

    /**
     * 6、查 ++:属性、分页
     * @param user
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/select/{page}/{size}")
    @ApiOperation (value = "select",notes = "分页查询")
    public Map<String, Object> selectUserByProperty(User user, @PathVariable int page, @PathVariable int size) {

        // 条件
        Criteria criteria1 = Criteria.where("userName").is(user.getUserName());
        Criteria criteria2 = Criteria.where("password").is(user.getPassword());
        Query query = new Query();
        if (user.getUserName() != null) {
            query.addCriteria(criteria1);
        }
        if (user.getPassword() != null) {
            query.addCriteria(criteria2);
        }

        // 数量
        long total = mongoTemplate.count(query, User.class);

        // 分页
        query.skip((page - 1) * size).limit(size);

        List<User> data = mongoTemplate.find(query, User.class);
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("data", data);
        map.put("total", total);

        return map;
    }
}


After the code is written, directly start the MongodbApplication startup class, open the swagger URL for testing (http: // localhost: 8080 / swagger-ui.html # /):
Insert picture description here
insert data:
Insert picture description hereview the database:
Insert picture description herehere, a simple demo It's finished.

Published 39 original articles · won praise 1 · views 4620

Guess you like

Origin blog.csdn.net/thetimelyrain/article/details/100184320