spring-boot 操作 mongodb 数据库

如何使用 spring-boot 操作 mongodb 数据库

配置文件:

spring:
  data:
    mongodb:
      host: 127.0.0.1
      database: fly_articleDb
      port: 27017
      # 可以采取 mysql 写法
      # uri: mongodb://127.0.0.1/fly_articleDb

依赖信息:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>3.1.1version>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>mongodb-javaartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>mongodb-javaname>
    <description>mongodb-javadescription>
    <properties>
        <java.version>17java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>
project>

Bean Comment 类:

package com.example.mongodb.bean;

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

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

/**
 * @author: fly
 * @Date: 2023-07-13 13:27
 * @Description:
 */
@ToString
@Data
// comment 集合(类名相同时,可以省略)
@Document(collection = "comment")
// 复合索引
//@CompoundIndex(def = "{'userId': 1, 'nickname': -1}")
public class Comment {
    // @Id // 可以省略,当变量名为 id
    private String id;
    // @Field("content") 变量名相同时可以省略
    // 评论内容
    private String content;
    // 发布时间
    private Date publishTime;
    // 添加单字段索引
    // 发布人id
    @Indexed
    private String userId;
    // 昵称
    private String nickname;
    // 评论的日期时间
    private LocalDateTime createDatetime;
    // 点赞数
    private Integer likeNum;
    // 回复数
    private Integer replyNum;
    // 状态 1 显示 0 隐藏
    private String state;
    // 上级id: 具体回复那个用户
    private String parentId;
    // 文章id
    private String articleId;
}

接口:

package com.example.mongodb.mongo;

import com.example.mongodb.bean.Comment;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * @author: fly
 * @Date: 2023-07-13 13:57
 * @Description: 评论接口
 */
public interface CommentRepository extends MongoRepository<Comment, String> {
}

实现:

package com.example.mongodb.service;

import com.example.mongodb.bean.Comment;
import com.example.mongodb.mongo.CommentRepository;
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.stereotype.Service;

import java.util.List;

/**
 * @author: fly
 * @Date: 2023-07-13 13:58
 * @Description:
 */
@Service
public class CommentService {
    private CommentRepository commentRepository;
    private MongoTemplate mongoTemplate;

    @Autowired
    public void setCommentRepository(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    @Autowired
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 保存或更新评论
     * @param comment 评论
     */
    public void saveComment(Comment comment) {
        // mongodb 会自动生成主键
        // 也可以自定义主键
        commentRepository.save(comment);
    }

    /**
     * 根据 id 删除评论
     * @param id 评论id
     */
    public void deleteCommentById(String id) {
        commentRepository.deleteById(id);
    }

    /**
     * 查找所有评论
     * @return 评论列表
     */
    public List<Comment> findComments() {
        return commentRepository.findAll();
    }

    /**
     * 根据id查询评论
     * @param id 评论id
     * @return 一条评论
     */
    public Comment findCommentById(String id) {
        return commentRepository.findById(id).get();
    }

    /**
     * 更新点赞
     */
    public void updateLikeNum(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("likeNum");
        mongoTemplate.updateFirst(query,update,Comment.class);
    }
}

入口类:

package com.example.mongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MongodbJavaApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongodbJavaApplication.class, args);
    }
}

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