水生的网络日志 水生的网络日志
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)

水生

记录我的所思、所学、所想
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)
  • 前言

  • Java核心

  • 企业级开发

    • Spring Boot开发

      • 创建Maven父子项目
      • Spring Boot整合MyBatis
      • Spring Boot整合Swagger
      • Spring Boot整合Redis实现缓存验证码
      • Spring Boot整合Spring Sercurity和JWT
      • Spring Boot整合Spring Task实现定时任务
      • Spring Boot整合ElasticSearch实现商品搜索
      • Spring Boot整合MongoDB实现文档操作
        • 项目使用框架介绍
          • Mongodb
          • Mongodb的安装和使用
          • Spring Data Mongodb
          • 常用注解
          • Sping Data方式的数据操作
          • 继承MongoRepository接口可以获得常用的数据操作方法
          • 可以使用衍生查询
          • 使用@Query注解可以用Mongodb的JSON查询语句进行查询
        • 整合Mongodb实现文档操作
          • 在pom.xml中添加相关依赖
          • 修改SpringBoot配置文件
          • 添加会员浏览记录文档对象MemberReadHistory
          • 添加MemberReadHistoryRepository接口用于操作Mongodb
          • 添加MemberReadHistoryService接口
          • 添加MemberReadHistoryService接口实现类MemberReadHistoryServiceImpl
          • 添加MemberReadHistoryController定义接口
        • 进行接口测试
          • 添加商品浏览记录到Mongodb
          • 查询Mongodb中的商品浏览记录
      • Spring Boot整合RabbitMQ实现延迟消息
    • Spring Cloud开发

  • 数据库

  • 计算机基础

  • 求职面试

  • 知识库
  • 企业级开发
  • Spring Boot开发
水生
2020-01-12
目录

Spring Boot整合MongoDB实现文档操作

本文主要介绍商城业务中整合Mongodb的过程,以实现商品浏览记录在Mongodb中的添加、删除、查询为例。

# 项目使用框架介绍

# Mongodb

Mongodb是为快速开发互联网Web应用而构建的数据库系统,其数据模型和持久化策略就是为了构建高读/写吞吐量和高自动灾备伸缩性的系统。

# Mongodb的安装和使用

  1. 下载Mongodb安装包,下载地址:https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.2.21-signed.msi
  2. 选择安装路径进行安装

img

img

  1. 在安装路径下创建data\db和data\log两个文件夹

img

  1. 在安装路径下创建mongod.cfg配置文件

    systemLog:
     destination: file
     path: D:\developer\env\MongoDB\data\log\mongod.log
    storage:
     dbPath: D:\developer\env\MongoDB\data\dbCopy to clipboardErrorCopied
    
    1
    2
    3
    4
    5
  2. 安装为服务(运行命令需要用管理员权限)

    D:\developer\env\MongoDB\bin\mongod.exe --config "D:\developer\env\MongoDB\mongod.cfg" --installCopy to clipboardErrorCopied
    
    1

    img

  3. 服务相关命令

    启动服务:net start MongoDB
    关闭服务:net stop MongoDB
    移除服务:D:\developer\env\MongoDB\bin\mongod.exe --removeCopy to clipboardErrorCopied
    
    1
    2
    3
  4. 下载客户端程序:https://download.robomongo.org/1.2.1/windows/robo3t-1.2.1-windows-x86_64-3e50a65.zip

  5. 解压到指定目录,打开robo3t.exe并连接到localhost:27017

img

# Spring Data Mongodb

和Spring Data Elasticsearch类似,Spring Data Mongodb是Spring提供的一种以Spring Data风格来操作数据存储的方式,它可以避免编写大量的样板代码。

# 常用注解

  • @Document:标示映射到Mongodb文档上的领域对象
  • @Id:标示某个域为ID域
  • @Indexed:标示某个字段为Mongodb的索引字段

# Sping Data方式的数据操作

# 继承MongoRepository接口可以获得常用的数据操作方法

img

# 可以使用衍生查询

在接口中直接指定查询方法名称便可查询,无需进行实现,以下为根据会员id按时间倒序获取浏览记录的例子。

/**
 * 会员商品浏览历史Repository
 * Created by macro on 2018/8/3.
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory,String> {
    /**
     * 根据会员id按时间倒序获取浏览记录
     * @param memberId 会员id
     */
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}Copy to clipboardErrorCopied
1
2
3
4
5
6
7
8
9
10
11

在idea中直接会提示对应字段

img

# 使用@Query注解可以用Mongodb的JSON查询语句进行查询
@Query("{ 'memberId' : ?0 }")
List<MemberReadHistory> findByMemberId(Long memberId);Copy to clipboardErrorCopied
1
2

# 整合Mongodb实现文档操作

# 在pom.xml中添加相关依赖

<!---mongodb相关依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>Copy to clipboardErrorCopied
1
2
3
4
5

# 修改SpringBoot配置文件

修改application.yml文件,在spring:data节点下添加Mongodb相关配置。

mongodb:
  host: localhost # mongodb的连接地址
  port: 27017 # mongodb的连接端口号
  database: mall-port # mongodb的连接的数据库Copy to clipboardErrorCopied
1
2
3
4

# 添加会员浏览记录文档对象MemberReadHistory

文档对象的ID域添加@Id注解,需要检索的字段添加@Indexed注解。

package com.sds.mongodb.nosql.mongodb.document;

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

import java.util.Date;

/**
 * @description: 用户商品浏览历史记录
 * @author: shuds
 * @date: 2022/1/12
 **/
@Document
public class MemberReadHistory {
    @Id
    private String id;
    @Indexed
    private Long memberId;
    private String memberNickname;
    private String memberIcon;
    @Indexed
    private Long productId;
    private String productName;
    private String productPic;
    private String productSubTitle;
    private String productPrice;
    private Date createTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Long getMemberId() {
        return memberId;
    }

    public void setMemberId(Long memberId) {
        this.memberId = memberId;
    }

    public String getMemberNickname() {
        return memberNickname;
    }

    public void setMemberNickname(String memberNickname) {
        this.memberNickname = memberNickname;
    }

    public String getMemberIcon() {
        return memberIcon;
    }

    public void setMemberIcon(String memberIcon) {
        this.memberIcon = memberIcon;
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductPic() {
        return productPic;
    }

    public void setProductPic(String productPic) {
        this.productPic = productPic;
    }

    public String getProductSubTitle() {
        return productSubTitle;
    }

    public void setProductSubTitle(String productSubTitle) {
        this.productSubTitle = productSubTitle;
    }

    public String getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(String productPrice) {
        this.productPrice = productPrice;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

# 添加MemberReadHistoryRepository接口用于操作Mongodb

继承MongoRepository接口,这样就拥有了一些基本的Mongodb数据操作方法,同时定义了一个衍生查询方法。

package com.sds.mongodb.nosql.mongodb.repository;

import com.sds.mongodb.nosql.mongodb.document.MemberReadHistory;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * 会员商品浏览历史Repository
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory,String> {
    /**
     * 根据会员id按时间倒序获取浏览记录
     * @param memberId 会员id
     */
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 添加MemberReadHistoryService接口

package com.sds.mongodb.service;

import com.sds.mongodb.nosql.mongodb.document.MemberReadHistory;

import java.util.List;

/**
 * 会员浏览记录管理Service
 * Created by shuds on 2022/1/12
 **/
public interface MemberReadHistoryService {
    /**
     * 生成浏览记录
     */
    int create(MemberReadHistory memberReadHistory);

    /**
     * 批量删除浏览记录
     */
    int delete(List<String> ids);

    /**
     * 获取用户浏览历史记录
     */
    List<MemberReadHistory> list(Long memberId);
}
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

# 添加MemberReadHistoryService接口实现类MemberReadHistoryServiceImpl

package com.sds.mongodb.service.impl;

import com.sds.mongodb.nosql.mongodb.document.MemberReadHistory;
import com.sds.mongodb.nosql.mongodb.repository.MemberReadHistoryRepository;
import com.sds.mongodb.service.MemberReadHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 会员浏览记录管理Service实现类
 * Created by shuds on 2022/1/12
 **/
@Service
public class MemberReadHistoryServiceImpl implements MemberReadHistoryService {
    @Autowired
    private MemberReadHistoryRepository memberReadHistoryRepository;
    @Override
    public int create(MemberReadHistory memberReadHistory) {
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        memberReadHistoryRepository.save(memberReadHistory);
        return 1;
    }

    @Override
    public int delete(List<String> ids) {
        List<MemberReadHistory> deleteList = new ArrayList<>();
        for(String id:ids){
            MemberReadHistory memberReadHistory = new MemberReadHistory();
            memberReadHistory.setId(id);
            deleteList.add(memberReadHistory);
        }
        memberReadHistoryRepository.deleteAll(deleteList);
        return ids.size();
    }

    @Override
    public List<MemberReadHistory> list(Long memberId) {
        return memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(memberId);
    }
}
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

# 添加MemberReadHistoryController定义接口

package com.sds.mongodb.controller;

import com.sds.mongodb.common.api.CommonResult;
import com.sds.mongodb.nosql.mongodb.document.MemberReadHistory;
import com.sds.mongodb.service.MemberReadHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员商品浏览记录管理Controller
 * Created by shuds on 2022/1/12
 **/
@RestController
@Api(tags = "MemberReadHistoryController", description = "会员商品浏览记录管理")
@RequestMapping("/member/readHistory")
public class MemberReadHistoryController {
    @Autowired
    private MemberReadHistoryService memberReadHistoryService;

    @ApiOperation("创建浏览记录")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody MemberReadHistory memberReadHistory) {
        int count = memberReadHistoryService.create(memberReadHistory);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("删除浏览记录")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("ids") List<String> ids) {
        int count = memberReadHistoryService.delete(ids);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("展示浏览记录")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MemberReadHistory>> list(Long memberId) {
        List<MemberReadHistory> memberReadHistoryList = memberReadHistoryService.list(memberId);
        return CommonResult.success(memberReadHistoryList);
    }
}

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

# 进行接口测试

# 添加商品浏览记录到Mongodb

image-20220112211101422

image-20220112211119527

# 查询Mongodb中的商品浏览记录

image-20220112211139202

image-20220112211154381

编辑 (opens new window)
#Spring Boot#MongoDB
上次更新: 2022/11/26, 22:18:38
Spring Boot整合ElasticSearch实现商品搜索
Spring Boot整合RabbitMQ实现延迟消息

← Spring Boot整合ElasticSearch实现商品搜索 Spring Boot整合RabbitMQ实现延迟消息→

最近更新
01
基于微服务案例的Maven实战
05-08
02
使用Seata彻底解决Spring Cloud中的分布式事务问题
11-26
03
Spring Boot整合RabbitMQ实现延迟消息
11-26
更多文章>
Theme by Vdoing | Copyright © 2019-2022 水生 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式