Springboot integration mongoDB case

table of Contents

1. Version description:

2. Code demonstration:

2.1: The directory structure is as follows

2.2: Pom file dependency introduction

2.3 Configure application.yml file

2.4: Abstract a data object stored in mongoDB, and add a user that needs to be stored in mongoDB;

2.5 Here, we will directly add, delete, modify and check mongoDB in the controller interface.

2.6 Result in the controller is a general return object, which can be defined according to your needs

3. Test results:


MongoDB is a non-relational database. Data operations on mongoDB are similar to operating documents. Create a database, and then create a collection, the collection in mongoDB is equivalent to the table in mysql.
After installing mongoDB, we then install the desktop visualization software studio 3t for mongodb, which is a very powerful mongoDB management software, and it is easy to download and install.

 

1. Version description:

springcloud:Greenwich.SR5

springboot:2.1.4.RELEASE

mongoDB:4.0.22

2. Code demonstration:

2.1: The directory structure is as follows

2.2: Pom file dependency introduction

  <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mongodb相关的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

2.3 Configure application.yml file

server:
  port: 1020

spring:
  main:
    # 允许bean定义重写
    allow-bean-definition-overriding: true
  application:
    name: IDEAL-MONGODB
  data:
    mongodb:
      uri: "mongodb://127.0.0.1:27017/test"


eureka:
  instance:
    prefer-ip-address: true # 注册服务的时候使用服务的ip地址
    hostname: elasticsearch-service
  client:
    service-url:
      defaultZone: http://localhost:1001/eureka/
    # 是否注册自身到eureka服务器
    register-with-eureka: true
    fetch-registry: true

 

2.4: Abstract a data object stored in mongoDB, and add a user that needs to be stored in mongoDB;

package com.demo.mongodb.dto;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

@Document
@Data
public class User {

    @Id
    private Long id;

    private String username;

    private String message;

    private String company;

    private String hobby;

    private Date createDate;

    private Date updateDate;

    @Override
    public String toString () {
        return JSONObject.toJSONString(this);
    }
}

2.5 Here, we will directly add, delete, modify and check mongoDB in the controller interface.

package com.demo.mongodb.controller;

import com.demo.mongodb.dto.Result;
import com.demo.mongodb.dto.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.data.mongodb.core.query.Update;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "mongoDB模块")
@RestController
@Slf4j
@RequestMapping("/mongodb")
public class MongodbController {

    @Autowired
    private MongoTemplate template;

    @ApiOperation(value = "新增单个用户", notes = "新增单个用户")
    @PostMapping(value = "/insert")
    public Result insertObj(@RequestBody  User user){
        log.info("新增用户入参=={}",user.toString());
        user.setCreateDate(new Date());
        User save = template.save(user);
        log.info("插入数据==={}",save.toString());
        return Result.ok("新增成功");
    }

    @ApiOperation(value = "批量新增用户", notes = "批量新增用户")
    @PostMapping(value = "/batchInsert")
    public Result batchInsert(@RequestBody List<User> users){
        log.info("批量新增用户入参=={}",users.toString());
        for(User item : users){
            template.save(item);
        }
        return Result.ok("批量新增成功");
    }

    @ApiOperation(value = "根据id查询", notes = "批量新增用户")
    @PostMapping(value = "/getById")
    public Result getById(@RequestBody  User user){
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        User one = template.findOne(query, User.class);
        return Result.ok(one);
    }

    @ApiOperation(value = "根据用户名称查询", notes = "根据用户名称查询")
    @PostMapping(value = "/getByUsername")
    public Result getByUsername(@RequestBody  User user){
        Query query = new Query(Criteria.where("username").is(user.getUsername()));
        User one = template.findOne(query, User.class);
        return Result.ok(one);
    }

    @ApiOperation(value = "更新用户hobby和company", notes = "更新用户hobby和company")
    @PutMapping(value = "/updateUser")
    public Result updateUser(@RequestBody  User user){
        log.info("更新用户入参==={}",user.toString());
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update  = new Update();
        update.set("hobby",user.getHobby());
        update.set("company",user.getCompany());
        UpdateResult updateResult = template.updateFirst(query, update, User.class);
        log.info("更新的结果==={}",updateResult.toString());
        return Result.ok("更新成功!");
    }

    @ApiOperation(value = "根据id删除用户", notes = "根据id删除用户")
    @DeleteMapping(value = "/deleteByID")
    public Result deleteByID(@RequestBody  User user){
        log.info("根据id删除用户请求==={}",user.toString());
        DeleteResult remove = template.remove(user);
        log.info("删除的结果==={}",remove);
        return Result.ok("删除成功");
    }


}

2.6 Result in the controller is a general return object, which can be defined according to your needs

package com.demo.mongodb.dto;

import lombok.Data;
import lombok.Getter;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * Description:统一接口返回体模板
 * @Author yangshilei
 * @Date 2019-05-15 14:16
 */
@Data
@Getter
public class Result<T> implements Serializable {

  private static final Integer SUCCESS_CODE = 200;
  private static final Integer REEOR_CODE = 400;
  private static final String SUCCESS_MESSAGE = "ok";

  private Integer code;

  private String message;

  private T data;

  protected Result(){}

  protected Result(Integer code, String message, T data){
    this.code = code;
    this.message = message;
    this.data = data;
  }

  public static <T> Result<T> ok(T data){
    return new Result<>(SUCCESS_CODE,SUCCESS_MESSAGE,data);
  }

  /**
   * 正确信息描述
   * @param message
   * @param <T>
   * @return
   */
  public static <T> Result<T> ok(String message) {
    return new Result(SUCCESS_CODE,message,null);
  }

  /**
   * 正确信息描述,同时返回错误信息
   * @param message
   * @param data
   * @param <T>
   * @return
   */
  public static <T> Result<T> ok(String message,T data){
    return new Result<T>(SUCCESS_CODE,message,data);
  }

  /**
   * 错误信息描述,适用于不需要规范化错误码的场景
   * @param message
   * @param <T>
   * @return
   */
  public static <T> Result<T> err (String message){
    return new Result<T>(REEOR_CODE,message,null);
  }

  /**
   * 错误信息描述,适用于需要规范错误码的场景
   * @param errMessage
   * @param <T>
   * @return
   */
  public static <T> Result<T> err(@NotNull  ErrMessage errMessage){
    return new Result<>(errMessage.code(),errMessage.desc(),null);
  }


}

Error code definition and description:

package com.demo.mongodb.dto;

/**
* @Author: yangshilei
* @Date: 2019/5/15 15:04
*/
public interface ErrMessage {

  /**
   * 错误响应状态码
   * @return
   */
  int code();

  /**
   * 错误描述
   * @return
   */
  String desc();
}

 

3. Test results:

Swagger test opens the interface, you can use postman to test if it is useless: add, delete, modify, check and other operations

View the data in the mongoDB database:


 

 

 

 

Guess you like

Origin blog.csdn.net/qq_37488998/article/details/112479860