Spring Boot集成MongoDB(单机模式)

前言

本文介绍了SpringBoot集成了MongoDB,利用SpringDataMongodb操作文章的评论的增、删、改、查过程。

环境

  • spring-boot(2.1.6)
  • mongodb(4.2.8)
  • spring-boot-starter-data-mongodb
  • IntelliJ IDEA (2019)

微服务模块搭建

搭建SpringBoot项目

比较简单,不再赘述

引入pom.xm

主要的包是spring-boot-starter-parent、spring-boot-starter-web、spring-boot-starter-data-mongodb,如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    
    com.mongo
    springboot-mongo
    0.0.1-SNAPSHOT
    springboot-mongo
    Demo project for Spring Boot connect mongoDB

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


配置application.yml

我搭的mongodb没加密码,比较简单的配置,可以通过官网提供的方式,也可以通过uri的方式,如下:

spring:
  data:
    mongodb:
      #主机地址
      host: 192.168.30.129
      database: article
      port: 27017
      #uri方式
      # uri: mongodb://192.168.30.129/article

评论实体类

评论的实体如下,我创建了一个复合索引,@CompoundIndex(def = "{'userId':1,'nickName':-1}"),它是名字和别名组成的,因为这两个基本一块用的,复合索引可以减少一个索引开销

package com.mongo.springbootmongo.entity;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.time.LocalDateTime;
import java.util.Date;

@Document(collection="comment")
@CompoundIndex(def = "{'userId':1,'nickName':-1}")
@Data
public class Comment {
    @Id
    private String id;//主键  
    //该属性对应mongodb的字段的名字,如果一致,则无需该注解  
    @Field("content")
    private String content;
    private Date publishTime = new Date();
    @Indexed
    private String userId;
    private String nickname;
    private LocalDateTime createDatetime = LocalDateTime.now();
    private Integer likeNum;
    private Integer replyNum;
    private String state;
    private String parentId;
    private String articleId;
}

Controller层代码

package com.mongo.springbootmongo.controller;

import com.mongo.springbootmongo.entity.Comment;
import com.mongo.springbootmongo.service.CommentService;
import com.mongo.springbootmongo.util.Result;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("comment")
public class CommentController {

    @Setter(onMethod_ = @Autowired)
    private CommentService commentService;

    @PostMapping
    public Result saveComment(@RequestBody Comment comment){

        return Result.success(commentService.saveComment(comment));
    }

    @GetMapping("/list")
    public Result get(){

        return Result.success(commentService.findCommentList());
    }
}

Service层实现

service层实现提供了5个方法,分别为:saveComment(保存评论)、updateComment(更新评论)、deleteCommentById(删除评论)、findCommentList(查询评论列表)、findCommentById(通过id查询评论)

package com.mongo.springbootmongo.service.impl;

import com.mongo.springbootmongo.dao.CommentRepository;
import com.mongo.springbootmongo.entity.Comment;
import com.mongo.springbootmongo.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final CommentRepository commentRepository;

    @Override
    public Comment saveComment(Comment comment) {
        return commentRepository.save(comment);
    }

    @Override
    public void updateComment(Comment comment) {
        commentRepository.save(comment);
    }

    @Override
    public void deleteCommentById(String id) {
        commentRepository.deleteById(id);
    }

    @Override
    public List findCommentList() {
        return commentRepository.findAll();
    }

    @Override
    public Optional findCommentById(String id) {
        return commentRepository.findById(id);
    }

}

DAO层

dao层直接继承了MongoRepository,比较简单

package com.mongo.springbootmongo.dao;
import com.mongo.springbootmongo.entity.Comment;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CommentRepository extends MongoRepository {

}

测试

本篇测试了两个接口,分别是保存评论和评论列表

  • 保存评论

里面postman测试如下:


保存评论postman测试
  • 评论列表


    评论列表postman测试

总结

本文主要介绍了通过SpringDataMongoDB操作连接MongoDB操作数据库的过程

你可能感兴趣的:(Spring Boot集成MongoDB(单机模式))