与SpringBoot集成
# 关于 spring-data-mongodb
提供了MongoTemplate与MongoRepository两种方式访问mongodb,在项目中可以灵活适用这两种方式操作mongodb
- MongoTemplate操作灵活
- MongoRepository操作简单,缺点:不够灵活,MongoTemplate正好可以弥补不足
# 搭建开发环境
# 新建项目
使用 Spring Initializr 快速初始化一个 Spring Boot 工程
# 修改POM
<?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 https://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.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.stt</groupId>
<artifactId>demo</artifactId>
<version>0.0.1</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</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
59
60
61
62
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
# 添加配置
- 修改
application.properties
文件
spring.data.mongodb.uri=mongodb://localhost:27017/test
1
- 启动项目,检查是否配置正常
# 添加实体
- 创建如下实体用于后续测试使用
- 使用 @Document 注解表示 文档,并指定文档名称
- 使用 @Id 指定该文档的主键
package com.stt.demo;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document("User")
public class User {
@Id
private String id;
private String name;
private Integer age;
private String email;
private String createDate;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 基于MongoTemplate
开发CRUD
常用方法
mongoTemplate.findAll(User.class): 查询User文档的全部数据
mongoTemplate.findById(<id>, User.class): 查询User文档id为id的数据
mongoTemplate.find(query, User.class);: 根据query内的查询条件查询
mongoTemplate.upsert(query, update, User.class): 修改
mongoTemplate.remove(query, User.class): 删除
mongoTemplate.insert(User): 新增
1
2
3
4
5
6
2
3
4
5
6
Query对象
- 创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)
- 精准条件:criteria.and(“key”).is(“条件”)
- 模糊条件:criteria.and(“key”).regex(“条件”)
- 封装条件:query.addCriteria(criteria)
- 大于(创建新的criteria):Criteria gt = Criteria.where(“key”).gt(“条件”)
- 小于(创建新的criteria):Criteria lt = Criteria.where(“key”).lt(“条件”)Query.addCriteria(new Criteria().andOperator(gt,lt));
- 一个query中只能有一个andOperator()。其参数也可以是Criteria数组
- 排序 :query.with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))
# 新增记录
package com.stt.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
@SpringBootTest
class MongoTemplateApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void createUser() {
User user = new User();
user.setName("stt");
user.setAge(22);
user.setEmail("work_stt@163.com");
User re = mongoTemplate.insert(user);
System.out.println(re);
}
}
// result
// User(id=61acc4a46eeb333442e675d9, name=stt, age=22, email=work_stt@163.com, createDate=null)
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
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
# 查询所有
@Test
public void findAll(){
List<User> all = mongoTemplate.findAll(User.class);
System.out.println(all);
}
1
2
3
4
5
2
3
4
5
# 通过id查询
@Test
public void getById(){
User re = mongoTemplate.findById("61acc4a46eeb333442e675d9", User.class);
System.out.println(re);
}
1
2
3
4
5
2
3
4
5
# 条件查询
@Test
public void findUserList() {
Query query = new Query(Criteria
.where("name").is("stt")
.and("age").is(22));
List<User> re = mongoTemplate.find(query, User.class);
System.out.println(re);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 模糊查询
@Test
public void findUserLikeName(){
String name = "st";
String regex = String.format("%s%s%s","^.*",name,".*$");
// CASE_INSENSITIVE 表示大小写不敏感
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("name").regex(pattern));
List<User> re = mongoTemplate.find(query, User.class);
System.out.println(re);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 分页查询
@Test
public void findUserPage() {
String name = "st";
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("name").regex(pattern));
long total = mongoTemplate.count(query, User.class);
int pageNo = 1;
int pageSize = 10;
query = query.skip((pageNo - 1) * pageSize).limit(pageSize);
List<User> users = mongoTemplate.find(query, User.class);
Map<String, Object> re = new HashMap<>();
re.put("list", users);
re.put("total", total);
System.out.println(re);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 修改记录
@Test
public void updateUser(){
User user = mongoTemplate.findById("61acc4a46eeb333442e675d9",User.class);
user.setName("stt_new");
user.setAge(23);
Query query = new Query(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name",user.getName());
update.set("age",user.getAge());
UpdateResult re = mongoTemplate.upsert(query, update, User.class);
long modifiedCount = re.getModifiedCount();
System.out.println(modifiedCount);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 删除操作
@Test
public void deleteUser(){
Query query = new Query(Criteria.where("_id").is("61acc4a46eeb333442e675d9"));
DeleteResult re = mongoTemplate.remove(query, User.class);
System.out.println(re.getDeletedCount());
}
1
2
3
4
5
6
2
3
4
5
6
# 基于MongoRepository
开发CRUD
Spring Data提供了对mongodb数据访问的支持,只需要继承MongoRepository类,按照Spring Data规范就可以了
# SpringData 方法定义规范
- 实现指定接口,通过方法名调用指定的方法实现
- 不是随便声明的,而需要符合一定的规范
- 查询方法以find | read | get开头
- 涉及条件查询时,条件的属性用条件关键字连接
- 要注意的是:条件属性首字母需要大写
- 支持属性的级联查询,但若当前类有符合条件的属性则优先使用,而不使用级联属性,若需要使用级联属性,则属性之间使用_强制进行连接
# 添加 UserRepository 接口
添加com.stt.demo.UserRepository类
package com.stt.demo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
// MongoRepository 第一个泛型是 User 第二个泛型是 ID的类型
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 新增记录
package com.stt.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import java.util.List;
@SpringBootTest
class MongoRepositoryApplicationTests {
@Autowired
private UserRepository repository;
@Test
public void createUser() {
User user = new User();
user.setName("stt");
user.setAge(22);
user.setEmail("work_stt@163.com");
User re = repository.save(user);
System.out.println(re);
// result
// User(id=61acceebdfa8a231d23eda37, name=stt, age=22, email=work_stt@163.com, createDate=null)
}
}
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
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
# 查询所有记录
@Test
public void findAllUser() {
List<User> all = repository.findAll();
System.out.println(all);
}
1
2
3
4
5
2
3
4
5
# 通过id查询
@Test
public void findById() {
User user = repository.findById("61acceebdfa8a231d23eda37").get();
System.out.println(user);
}
1
2
3
4
5
2
3
4
5
# 条件查询
// 条件查询
@Test
public void findUserList() {
User user = new User();
user.setName("stt");
user.setAge(22);
Example<User> example = Example.of(user);
List<User> re = repository.findAll(example);
System.out.println(re);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 模糊查询
@Test
public void findUserLikeName() {
ExampleMatcher exampleMatcher = ExampleMatcher
.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 字符串包含
.withIgnoreCase(true); // 忽略大消息
User user = new User();
user.setName("st");
Example<User> example = Example.of(user,exampleMatcher);
List<User> re = repository.findAll(example);
System.out.println(re);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 分页查询
@Test
public void findUserPage(){
// 查询条件
ExampleMatcher exampleMatcher = ExampleMatcher
.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 字符串包含
.withIgnoreCase(true); // 忽略大消息
User user = new User();
user.setName("st");
Example<User> example = Example.of(user,exampleMatcher);
// 分页参数
Sort sort = Sort.by(Sort.Direction.DESC,"age");
// 0 为第一页
Pageable pageable = PageRequest.of(0,10,sort);
Page<User> page = repository.findAll(example, pageable);
System.out.println(page);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 修改记录
@Test
public void updateUser(){
User user = repository.findById("61acceebdfa8a231d23eda37").get();
user.setName("stt_new");
user.setAge(23);
User newUser = repository.save(user);
System.out.println(newUser);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 删除记录
@Test
public void removeUser(){
repository.deleteById("61acceebdfa8a231d23eda37");
}
1
2
3
4
2
3
4
Last Updated: 2022/01/16, 11:29:51