9.MongoDB Demo

 

文章评论

1.需求分析

文章评论功能

需要实现以下功能:

  1. 基本增删改查API
  2. 根据文章id查询评论
  3. 评论点赞

2.数据库设计

表: articledb

字段名称 字段含义 字段类型 备注
_id ID ObjectId或String Mongo的主键的字段
articleid 文章ID String
content 评论内容 String
userid 评论人ID String
nickname 评论人昵称 String
createdatetime 评论的日期时间 Date
likenum 点赞数 Int32
replynum 回复数 Int32
state 状态 String 0:不可见;1:可见;
parentid 上级ID String 如果为0表示文章的顶级评论

3.使用技术

(1) mongodb-driver

mongodb-driver 是 mongo 官方推出的 java 连接 mongoDB 的驱动包,相当于 JDBC 驱动。我们通过一个入门的案例来了解 mongodb-driver 的基本使用

(2) SpringDataMongoDB

SpringData 家族成员之一,用于操作 MongoDB 的持久层框架,封装了底层的 mongodb-driver

4.项目搭建

(1) 新建一个 SpringBoot 或 Maven 工程

(2) pom.xml 文件引入依赖

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
<?xml version="1.0" encoding="UTF-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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>

<groupId>org.example</groupId>
<artifactId>article</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>

</dependencies>

</project>

(3) 创建 application.yml

1
2
3
4
5
6
7
8
spring:
data:
mongodb:
host: 192.168.76.128
port: 27017
database: articledb
# 或者通过uri 方式连接
# uri: mongodb://192.168.76.128:27017/articledb

(4) 创建启动类

运行启动类,看项目能否正常启动

1
2
3
4
5
6
7
8
9
10
11
package com.learn.article;

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

@SpringBootApplication
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class);
}
}

(5) 创建实体类

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
111
112
113
114
115
116
117
118
119
120
121
122
package com.learn.article.po;

import org.springframework.data.annotation.Id;
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.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 文章评论实体类
*/
// 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
// @Document(collection="mongodb 对应 collection 名")
// 可以省略,如果省略,则默认使用类名小写映射集合
@Document(collection="comment")
// 复合索引
// @CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
public class Comment implements Serializable {
// 主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
@Id
private String id; // 主键
// 该属性对应mongodb的字段的名字,如果一致,则无需该注解
@Field("content")
private String content; // 吐槽内容
private Date publishtime; // 发布日期
// 添加了一个单字段的索引
@Indexed
private String userid; // 发布人ID
private String nickname; // 昵称
private LocalDateTime createdatetime; // 评论的日期时间
private Integer likenum; // 点赞数
private Integer replynum; // 回复数
private String state; // 状态
private String parentid; // 上级ID
private String articleid;

// getter and setter
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getPublishtime() {
return publishtime;
}
public void setPublishtime(Date publishtime) {
this.publishtime = publishtime;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public LocalDateTime getCreatedatetime() {
return createdatetime;
}
public void setCreatedatetime(LocalDateTime createdatetime) {
this.createdatetime = createdatetime;
}
public Integer getLikenum() {
return likenum;
}
public void setLikenum(Integer likenum) {
this.likenum = likenum;
}
public Integer getReplynum() {
return replynum;
}
public void setReplynum(Integer replynum) {
this.replynum = replynum;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getParentid() {return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getArticleid() {
return articleid;
}
public void setArticleid(String articleid) {
this.articleid = articleid;
}

@Override
public String toString() {
return "Comment{" +
"id='" + id + '\'' +
", content='" + content + '\'' +
", publishtime=" + publishtime +
", userid='" + userid + '\'' +
", nickname='" + nickname + '\'' +
", createdatetime=" + createdatetime +
", likenum=" + likenum +
", replynum=" + replynum +
", state='" + state + '\'' +
", parentid='" + parentid + '\'' +
", articleid='" + articleid + '\'' +
'}';
}

}

说明:

索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过 Mongo 的命令来添加,也可以在 Java 的实体类中通过注解添加

1)单字段索引注解 @Indexed ( org.springframework.data.mongodb.core.index.Indexed.class )

2)复合索引注解 @CompoundIndex ( org.springframework.data.mongodb.core.index.CompoundIndex.class )

5.基本增删改查

(1) 新建 Dao

1
2
3
4
5
6
7
8
package com.learn.article.dao;

import com.learn.article.po.Comment;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CommentRepository extends MongoRepository<Comment, String> {

}

(2) 新建 Service

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
package com.learn.article.service;

import com.learn.article.dao.CommentRepository;
import com.learn.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {

@Autowired
private CommentRepository commentRepository;

/**
* 保存一个评论
* @param comment
*/
public void saveComment(Comment comment) {
//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
commentRepository.save(comment);
}

/**
* 更新评论
* @param comment
*/
public void updateComment(Comment comment) {
commentRepository.save(comment);
}

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

/**
* 查询所有评论
* @return
*/
public List<Comment> findCommentList() {
return commentRepository.findAll();
}

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

(3) 新建 JUnit 测试类

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
package com.learn.article.service;

import com.learn.article.ArticleApplication;
import com.learn.article.po.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.List;

// SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
// SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

@Autowired
private CommentService commentService;

@Test
public void testFindCommentList() {
List<Comment> commentList = commentService.findCommentList();
for (int i = 0; i < commentList.size(); i++) {
System.out.println(commentList.get(i));
}
// Comment{id='1', content='我们不应该把清晨浪费在手机上,健康很重要,一杯温水幸福你我他。', publishtime=null, userid='1002', nickname='相忘于江湖', createdatetime=1970-01-01T08:00, likenum=1000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='2', content='我夏天空腹喝凉开水,冬天喝温开水', publishtime=null, userid='1005', nickname='伊人憔悴', createdatetime=1970-01-01T08:00, likenum=888, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='3', content='我一直喝凉开水,冬天夏天都喝。', publishtime=null, userid='1004', nickname='杰克船长', createdatetime=2019-08-06T09:05:06.321, likenum=666, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='4', content='专家说不能空腹吃饭,影响健康。', publishtime=null, userid='1003', nickname='凯撒', createdatetime=2019-08-06T16:18:35.288, likenum=2000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='5', content='研究表明,刚烧开的水千万不能喝,因为烫嘴。', publishtime=null, userid='1003', nickname='凯撒', createdatetime=2019-08-06T19:01:02.521, likenum=3000, replynum=null, state='1', parentid='null', articleid='100001'}
}

@Test
public void testFindCommentById() {
Comment comment = commentService.findCommentById("1");
System.out.println(comment);
// Comment{id='1', content='我们不应该把清晨浪费在手机上,健康很重要,一杯温水幸福你我他。', publishtime=null, userid='1002', nickname='相忘于江湖', createdatetime=1970-01-01T08:00, likenum=1000, replynum=null, state='1', parentid='null', articleid='100001'}
}

@Test
public void testSaveComment() {
Comment comment=new Comment();
comment.setArticleid("100000");
comment.setContent("测试添加的数据");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1003");
comment.setNickname("凯撒大帝");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);

commentService.saveComment(comment);

List<Comment> commentList = commentService.findCommentList();
for (int i = 0; i < commentList.size(); i++) {
System.out.println(commentList.get(i));
}
// Comment{id='1', content='我们不应该把清晨浪费在手机上,健康很重要,一杯温水幸福你我他。', publishtime=null, userid='1002', nickname='相忘于江湖', createdatetime=1970-01-01T08:00, likenum=1000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='2', content='我夏天空腹喝凉开水,冬天喝温开水', publishtime=null, userid='1005', nickname='伊人憔悴', createdatetime=1970-01-01T08:00, likenum=888, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='3', content='我一直喝凉开水,冬天夏天都喝。', publishtime=null, userid='1004', nickname='杰克船长', createdatetime=2019-08-06T09:05:06.321, likenum=666, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='4', content='专家说不能空腹吃饭,影响健康。', publishtime=null, userid='1003', nickname='凯撒', createdatetime=2019-08-06T16:18:35.288, likenum=2000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='5', content='研究表明,刚烧开的水千万不能喝,因为烫嘴。', publishtime=null, userid='1003', nickname='凯撒', createdatetime=2019-08-06T19:01:02.521, likenum=3000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='641ba8c8107cbd0910a0e93c', content='测试添加的数据', publishtime=null, userid='1003', nickname='凯撒大帝', createdatetime=2023-03-23T09:18:00.629, likenum=0, replynum=0, state='1', parentid='null', articleid='100000'}

}
}

6.更新数值字段的值

$inc 方法

更新点赞数

(1) 修改 CommentService

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
package com.learn.article.service;

import com.learn.article.dao.CommentRepository;
import com.learn.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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;

@Service
public class CommentService {

@Autowired
private CommentRepository commentRepository;

@Autowired
private MongoTemplate mongoTemplate;

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

/**
* 点赞数+1
* @param id
*/
public void updateCommentLikenum(String id) {
// 查询对象
Query query = Query.query(Criteria.where("_id").is(id));
// 更新对象
Update update = new Update();
// 递增 $inc
update.inc("likenum");

// 执行更新
// 参数1:查询对象
// 参数2:更新对象
// 参数3:集合的名字或实体类的类型Comment.class
mongoTemplate.updateFirst(query, update, Comment.class);
}

}

(2) 添加测试方法

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
package com.learn.article.service;

import com.learn.article.ArticleApplication;
import com.learn.article.po.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.List;

// SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
// SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

@Autowired
private CommentService commentService;

@Test
public void testUpdateCommentLikenum() {
String id = "3";
Comment commentBefore = commentService.findCommentById(id);
System.out.println(commentBefore);
// Comment{id='3', content='我一直喝凉开水,冬天夏天都喝。', publishtime=null, userid='1004', nickname='杰克船长', createdatetime=2019-08-06T09:05:06.321, likenum=666, replynum=null, state='1', parentid='null', articleid='100001'}

commentService.updateCommentLikenum(id);

Comment commentAfter = commentService.findCommentById(id);
System.out.println(commentAfter);
// Comment{id='3', content='我一直喝凉开水,冬天夏天都喝。', publishtime=null, userid='1004', nickname='杰克船长', createdatetime=2019-08-06T09:05:06.321, likenum=667, replynum=null, state='1', parentid='null', articleid='100001'}
}
}