Springboot集成MongoDB案例

一、Linux安装mongodb

1.创建yum源文件

cd /etc/yum.repos.d
vim mongodb-org-4.0.repo

2.添加下载配置文件(这里使用阿里云的源),保存退出

[mngodb-org]
name=MongoDB Repository
baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/7Server/mongodb-org/4.0/x86_64/
gpgcheck=0
enabled=1

3.更新yum

yum update -y

4.安装mongodb

yum install mongodb-org -y

5.查看mongodban

whereis mongod

6.修改配置

vim /etc/mongod.conf

bindIp: 172.0.0.1 改为 bindIp: 0.0.0.0(注意冒号与ip之间需要一个空格),保存退出

7.启动服务

systemctl start mongod

 

二、使用案例

1.maven依赖

 
        
            io.springfox
            springfox-boot-starter
            3.0.0
        
        
        
            com.github.xiaoymin
            knife4j-spring-boot-starter
            3.0.3
        

        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        

2.yml配置

server:
  port: 9082

spring:
  data:
    mongodb:
      host: 10.10.10.110   #同127.0.0.1
      port: 27017
      database: test    #指定操作的数据库

#swagger文档开启/关闭
springfox:
  documentation:
    auto-startup: true
#knife4j
knife4j:
  production: false # 开启/屏蔽文档资源

3.代码

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author :jerry
 * @date :Created in 2022/5/28 10:30
 * @description:
 * @version: V1.1
 *  *Swagger3API文档的配置
 *  knife4j文档地址(端口号根据自己项目配置): http://localhost:8081/doc.html#
 *  swagger文档地址(端口号根据自己项目配置):http://localhost:8081/swagger-ui/index.html#/
 */
@Configuration
@EnableOpenApi
@EnableKnife4j
public class Swagger3Config {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
//                .groupName("webApi")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cetc.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    @Bean
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI接口文档")
                .description("接口文档Swagger-Bootstrap版")
                .termsOfServiceUrl("http://localhost:8081/swagger-ui/index.html#/")
                .contact(new Contact("jerry","http://localhost:8081/doc.html#", "[email protected]"))
                .version("1.0")
                .license("jerry")
                .build();
    }
}
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author :jerry
 * @date :Created in 2022/11/30 11:13
 * @description:
 * @version: V1.1
 */

@Data
public class Student {

    @ApiModelProperty("id")
    private Long id;

    @ApiModelProperty("姓名")
    private String name;

    @ApiModelProperty("性别")
    private String sex;

    @ApiModelProperty("年龄")
    private Integer age;

    @ApiModelProperty("班级")
    private String className;

    @ApiModelProperty("开始页")
    private int start;

    @ApiModelProperty("每页数量")
    private int size;

}
import com.cetc.common.CommonResultVo;
import com.cetc.entity.Student;
import com.mongodb.client.MongoCollection;
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.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;
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.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author :jerry
 * @date :Created in 2022/11/30 11:15
 * @description:
 * @version: V1.1
 */
@Api(tags = "学生信息")
@Slf4j
@RestController
@RequestMapping("/db")
public class StudentController {

    @Autowired
    private MongoTemplate mongoTemplate;


    @ApiOperation(value = "创建表集合")
    @GetMapping("/createCollection")
    public CommonResultVo createCollection(String tableName){
        MongoCollection collection = mongoTemplate.createCollection(tableName);
        return CommonResultVo.success(collection);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/pageList")
    public CommonResultVo pageList( Student student) {
        Query query = new Query();
        //条件查询
        if(StringUtils.isNotEmpty(student.getName())){
            query.addCriteria(Criteria.where("name").is(student.getName()));
        }
        if (!Objects.isNull(student.getAge())) {
            query.addCriteria(Criteria.where("age").is(student.getAge()));
        }
        //分页条件
        query.skip(student.getStart());
        query.limit(student.getSize());

        //排序
        query.with(Sort.by(Sort.Direction.DESC, "age"));

        List lis = mongoTemplate.find(query, Student.class);
        return CommonResultVo.success(lis);
    }

    @ApiOperation(value = "根据Id查询单个")
    @GetMapping("/findById/{id}")
    public CommonResultVo findById(@PathVariable("id") Long id){
        Student stu = mongoTemplate.findById(id, Student.class);
        return CommonResultVo.success(stu);
    }

    @ApiOperation(value = "新增")
    @PostMapping("/save")
    public CommonResultVo save(@RequestBody Student student){
        return CommonResultVo.success( mongoTemplate.save(student));
    }

    @ApiOperation(value = "修改")
    @PostMapping("/update")
    public CommonResultVo update(@RequestBody Student student){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(student.getId()));
        Update update = new Update();
        if(StringUtils.isNotEmpty(student.getName())) {
            update.set("name",student.getName());
        }
        if(!Objects.isNull(student.getAge())){
            update.set("age",student.getAge());
        }
        if(StringUtils.isNotEmpty(student.getSex())){
            update.set("sex",student.getSex());
        }
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Student.class);
        return CommonResultVo.success(updateResult);
    }


    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public CommonResultVo delete(@RequestBody Student student){
        //条件删除
        Query query = new Query();
        if(!Objects.isNull(student.getId())){
            query.addCriteria(Criteria.where("id").is(student.getId()));
        }
        if(StringUtils.isNotEmpty(student.getName())){
            query.addCriteria(Criteria.where("name").is(student.getName()));
        }
        if (!Objects.isNull(student.getAge())) {
            query.addCriteria(Criteria.where("age").is(student.getAge()));
        }
        DeleteResult deleteResult = mongoTemplate.remove(query, Student.class);
        return CommonResultVo.success(deleteResult);
    }

    @ApiOperation(value = "查询所有")
    @GetMapping("/findAll")
    public CommonResultVo findAll(){
        List all = mongoTemplate.findAll(Student.class);
        return CommonResultVo.success(all);
    }
}
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;


@Getter
@Setter
@Builder
public class CommonResultVo {

    private int code;
    private String message;
    private T data;

    protected CommonResultVo() {
    }

    protected CommonResultVo(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 成功返回结果
     *
     */
    public static  CommonResultVo success() {
        return new CommonResultVo(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static  CommonResultVo success(T data) {
        return new CommonResultVo(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     * @param  message 提示信息
     */
    public static  CommonResultVo success(T data, String message) {
        return new CommonResultVo(ResultCode.SUCCESS.getCode(), message, data);
    }

    /**
     * 失败返回结果
     * @param resultCode 错误码
     */
    public static  CommonResultVo failed(ResultCode resultCode) {
        return new CommonResultVo(resultCode.getCode(), resultCode.getMessage(), null);
    }

    /**
     * 失败返回结果
     * @param resultCode 错误码
     * @param message 错误信息
     */
    public static  CommonResultVo failed(ResultCode resultCode, String message) {
        return new CommonResultVo(resultCode.getCode(), message, null);
    }

    /**
     * 失败返回结果
     * @param message 提示信息
     */
    public static  CommonResultVo failed(String message) {
        return new CommonResultVo(ResultCode.FAILED.getCode(), message, null);
    }

    /**
     * 失败返回结果
     */
    public static  CommonResultVo failed() {
        return failed(ResultCode.FAILED);
    }
}
import lombok.Getter;
import lombok.Setter;



public enum ResultCode {
    SUCCESS(0, "操作成功"),
    FAILED(-1, "操作失败"),
    VALIDATE_FAILED(404, "参数检验失败"),
    UNAUTHORIZED(401, "暂未登录或token已经过期"),
    FORBIDDEN(403, "没有相关权限");

    @Setter
    @Getter
    private int code;

    @Setter
    @Getter
    private String message;

    private ResultCode(int code, String message) {
        this.code = code;
        this.message = message;
    }


}

Springboot集成MongoDB案例_第1张图片

 Springboot集成MongoDB案例_第2张图片

你可能感兴趣的:(java,mongodb,mongodb,数据库)