• 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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    依赖信息:

    
    <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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    接口:

    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> {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    实现:

    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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    入口类:

    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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    一起Talk Android吧(第三百七十九回:让ViewPager一屏幕显示三页)
    ASP.NET Core 6框架揭秘实例演示[04]:自定义依赖注入框架
    路由重分布的概念与配置
    03-Redis 凭什么这么快
    数据挖掘与机器学习
    前端---ES5知识点小梳理三
    个推TechDay直播回顾 | 分享基于Flink的实时数仓搭建秘诀 附课件下载
    物联网常见协议篇
    删除表中的数据
    PMP项目管理中的各种图
  • 原文地址:https://blog.csdn.net/qq_56402474/article/details/133514935