Skip to content

Commit f6f86ec

Browse files
committed
✨ spring-boot-demo-mongodb 完成
1 parent b7c9819 commit f6f86ec

File tree

2 files changed

+332
-0
lines changed

2 files changed

+332
-0
lines changed

spring-boot-demo-mongodb/README.md

+332
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
# spring-boot-demo-mongodb
2+
3+
> 此 demo 主要演示了 Spring Boot 如何集成 MongoDB,使用官方的 starter 实现增删改查。
4+
5+
## 注意
6+
7+
作者编写本demo时,MongoDB 最新版本为 `4.1`,使用 docker 运行,下面是所有步骤:
8+
9+
1. 下载镜像:`docker pull mongo:4.1`
10+
2. 运行容器:`docker run -d -p 27017:27017 -v /Users/yangkai.shen/docker/mongo/data:/data/db --name mongo-4.1 mongo:4.1`
11+
3. 停止容器:`docker stop mongo-4.1`
12+
4. 启动容器:`docker start mongo-4.1`
13+
14+
## pom.xml
15+
16+
```xml
17+
<?xml version="1.0" encoding="UTF-8"?>
18+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
19+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
20+
<modelVersion>4.0.0</modelVersion>
21+
22+
<artifactId>spring-boot-demo-mongodb</artifactId>
23+
<version>1.0.0-SNAPSHOT</version>
24+
<packaging>jar</packaging>
25+
26+
<name>spring-boot-demo-mongodb</name>
27+
<description>Demo project for Spring Boot</description>
28+
29+
<parent>
30+
<groupId>com.xkcoding</groupId>
31+
<artifactId>spring-boot-demo</artifactId>
32+
<version>1.0.0-SNAPSHOT</version>
33+
</parent>
34+
35+
<properties>
36+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
37+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
38+
<java.version>1.8</java.version>
39+
</properties>
40+
41+
<dependencies>
42+
<dependency>
43+
<groupId>org.springframework.boot</groupId>
44+
<artifactId>spring-boot-starter</artifactId>
45+
</dependency>
46+
47+
<dependency>
48+
<groupId>org.springframework.boot</groupId>
49+
<artifactId>spring-boot-starter-data-mongodb</artifactId>
50+
</dependency>
51+
52+
<dependency>
53+
<groupId>org.springframework.boot</groupId>
54+
<artifactId>spring-boot-starter-test</artifactId>
55+
<scope>test</scope>
56+
</dependency>
57+
58+
<dependency>
59+
<groupId>cn.hutool</groupId>
60+
<artifactId>hutool-all</artifactId>
61+
</dependency>
62+
63+
<dependency>
64+
<groupId>com.google.guava</groupId>
65+
<artifactId>guava</artifactId>
66+
</dependency>
67+
68+
<dependency>
69+
<groupId>org.projectlombok</groupId>
70+
<artifactId>lombok</artifactId>
71+
<optional>true</optional>
72+
</dependency>
73+
</dependencies>
74+
75+
<build>
76+
<finalName>spring-boot-demo-mongodb</finalName>
77+
<plugins>
78+
<plugin>
79+
<groupId>org.springframework.boot</groupId>
80+
<artifactId>spring-boot-maven-plugin</artifactId>
81+
</plugin>
82+
</plugins>
83+
</build>
84+
85+
</project>
86+
```
87+
88+
## application.yml
89+
90+
```yaml
91+
spring:
92+
data:
93+
mongodb:
94+
host: localhost
95+
port: 27017
96+
database: article_db
97+
logging:
98+
level:
99+
org.springframework.data.mongodb.core: debug
100+
```
101+
102+
## Article.java
103+
104+
```java
105+
/**
106+
* <p>
107+
* 文章实体类
108+
* </p>
109+
*
110+
* @package: com.xkcoding.mongodb.model
111+
* @description: 文章实体类
112+
* @author: yangkai.shen
113+
* @date: Created in 2018-12-28 16:21
114+
* @copyright: Copyright (c) 2018
115+
* @version: V1.0
116+
* @modified: yangkai.shen
117+
*/
118+
@Data
119+
@Builder
120+
@NoArgsConstructor
121+
@AllArgsConstructor
122+
public class Article {
123+
/**
124+
* 文章id
125+
*/
126+
@Id
127+
private Long id;
128+
129+
/**
130+
* 文章标题
131+
*/
132+
private String title;
133+
134+
/**
135+
* 文章内容
136+
*/
137+
private String content;
138+
139+
/**
140+
* 创建时间
141+
*/
142+
private Date createTime;
143+
144+
/**
145+
* 更新时间
146+
*/
147+
private Date updateTime;
148+
149+
/**
150+
* 点赞数量
151+
*/
152+
private Long thumbUp;
153+
154+
/**
155+
* 访客数量
156+
*/
157+
private Long visits;
158+
159+
}
160+
```
161+
162+
## ArticleRepository.java
163+
164+
```java
165+
/**
166+
* <p>
167+
* 文章 Dao
168+
* </p>
169+
*
170+
* @package: com.xkcoding.mongodb.repository
171+
* @description: 文章 Dao
172+
* @author: yangkai.shen
173+
* @date: Created in 2018-12-28 16:30
174+
* @copyright: Copyright (c) 2018
175+
* @version: V1.0
176+
* @modified: yangkai.shen
177+
*/
178+
public interface ArticleRepository extends MongoRepository<Article, Long> {
179+
/**
180+
* 根据标题模糊查询
181+
*
182+
* @param title 标题
183+
* @return 满足条件的文章列表
184+
*/
185+
List<Article> findByTitleLike(String title);
186+
}
187+
```
188+
189+
## ArticleRepositoryTest.java
190+
191+
```java
192+
/**
193+
* <p>
194+
* 测试操作 MongoDb
195+
* </p>
196+
*
197+
* @package: com.xkcoding.mongodb.repository
198+
* @description: 测试操作 MongoDb
199+
* @author: yangkai.shen
200+
* @date: Created in 2018-12-28 16:35
201+
* @copyright: Copyright (c) 2018
202+
* @version: V1.0
203+
* @modified: yangkai.shen
204+
*/
205+
@Slf4j
206+
public class ArticleRepositoryTest extends SpringBootDemoMongodbApplicationTests {
207+
@Autowired
208+
private ArticleRepository articleRepo;
209+
210+
@Autowired
211+
private MongoTemplate mongoTemplate;
212+
213+
@Autowired
214+
private Snowflake snowflake;
215+
216+
/**
217+
* 测试新增
218+
*/
219+
@Test
220+
public void testSave() {
221+
Article article = new Article(1L, RandomUtil.randomString(20), RandomUtil.randomString(150), DateUtil.date(), DateUtil
222+
.date(), 0L, 0L);
223+
articleRepo.save(article);
224+
log.info("【article】= {}", JSONUtil.toJsonStr(article));
225+
}
226+
227+
/**
228+
* 测试新增列表
229+
*/
230+
@Test
231+
public void testSaveList() {
232+
List<Article> articles = Lists.newArrayList();
233+
for (int i = 0; i < 10; i++) {
234+
articles.add(new Article(snowflake.nextId(), RandomUtil.randomString(20), RandomUtil.randomString(150), DateUtil
235+
.date(), DateUtil.date(), 0L, 0L));
236+
}
237+
articleRepo.saveAll(articles);
238+
239+
log.info("【articles】= {}", JSONUtil.toJsonStr(articles.stream()
240+
.map(Article::getId)
241+
.collect(Collectors.toList())));
242+
}
243+
244+
/**
245+
* 测试更新
246+
*/
247+
@Test
248+
public void testUpdate() {
249+
articleRepo.findById(1L).ifPresent(article -> {
250+
article.setTitle(article.getTitle() + "更新之后的标题");
251+
article.setUpdateTime(DateUtil.date());
252+
articleRepo.save(article);
253+
log.info("【article】= {}", JSONUtil.toJsonStr(article));
254+
});
255+
}
256+
257+
/**
258+
* 测试删除
259+
*/
260+
@Test
261+
public void testDelete() {
262+
// 根据主键删除
263+
articleRepo.deleteById(1L);
264+
265+
// 全部删除
266+
articleRepo.deleteAll();
267+
}
268+
269+
/**
270+
* 测试点赞数、访客数,使用save方式更新点赞、访客
271+
*/
272+
@Test
273+
public void testThumbUp() {
274+
articleRepo.findById(1L).ifPresent(article -> {
275+
article.setThumbUp(article.getThumbUp() + 1);
276+
article.setVisits(article.getVisits() + 1);
277+
articleRepo.save(article);
278+
log.info("【标题】= {}【点赞数】= {}【访客数】= {}", article.getTitle(), article.getThumbUp(), article.getVisits());
279+
});
280+
}
281+
282+
/**
283+
* 测试点赞数、访客数,使用更优雅/高效的方式更新点赞、访客
284+
*/
285+
@Test
286+
public void testThumbUp2() {
287+
Query query = new Query();
288+
query.addCriteria(Criteria.where("_id").is(1L));
289+
Update update = new Update();
290+
update.inc("thumbUp", 1L);
291+
update.inc("visits", 1L);
292+
mongoTemplate.updateFirst(query, update, "article");
293+
294+
articleRepo.findById(1L)
295+
.ifPresent(article -> log.info("【标题】= {}【点赞数】= {}【访客数】= {}", article.getTitle(), article.getThumbUp(), article
296+
.getVisits()));
297+
}
298+
299+
/**
300+
* 测试分页排序查询
301+
*/
302+
@Test
303+
public void testQuery() {
304+
Sort sort = Sort.by("thumbUp", "updateTime").descending();
305+
PageRequest pageRequest = PageRequest.of(0, 5, sort);
306+
Page<Article> all = articleRepo.findAll(pageRequest);
307+
log.info("【总页数】= {}", all.getTotalPages());
308+
log.info("【总条数】= {}", all.getTotalElements());
309+
log.info("【当前页数据】= {}", JSONUtil.toJsonStr(all.getContent()
310+
.stream()
311+
.map(article -> "文章标题:" + article.getTitle() + "点赞数:" + article.getThumbUp() + "更新时间:" + article.getUpdateTime())
312+
.collect(Collectors.toList())));
313+
}
314+
315+
/**
316+
* 测试根据标题模糊查询
317+
*/
318+
@Test
319+
public void testFindByTitleLike() {
320+
List<Article> articles = articleRepo.findByTitleLike("更新");
321+
log.info("【articles】= {}", JSONUtil.toJsonStr(articles));
322+
}
323+
324+
}
325+
```
326+
327+
## 参考
328+
329+
1. Spring Data MongoDB 官方文档:https://docs.spring.io/spring-data/mongodb/docs/2.1.2.RELEASE/reference/html/
330+
2. MongoDB 官方镜像地址:https://hub.docker.com/_/mongo
331+
3. MongoDB 官方快速入门:https://docs.mongodb.com/manual/tutorial/getting-started/
332+
4. MongoDB 官方文档:https://docs.mongodb.com/manual/

spring-boot-demo-mongodb/src/main/resources/application.properties

Whitespace-only changes.

0 commit comments

Comments
 (0)