![ee07d85f5e135929fe51a2a150d933c3.png](https://i-blog.csdnimg.cn/blog_migrate/ad3b50286d7a0b5c3ea3329aafe83dc7.jpeg)
本节使用SpringBoot 2.1.9.RELEASE,示例源码在:https://github.com/laolunsi/spring-boot-examples
SpringBoot可以非常方便地引入和操作MongoDB。本节分两部分,记录个人学习SpringBoot使用MongoDB数据库的一些知识。
第一部分是一个简单的springboot连接mongo的demo,测试查询功能。
第二部分是基于mongo实现的增删改查数据示例。
一、A simple demo
首先来演示SpringBoot项目引入MongoDB,以及一个简单的findAll操作。
maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
环境配置:
application.yml文件中写入如下配置,test表示MongoDB中的test表
spring:
data:
mongodb:
uri: "mongodb://localhost:27017/test"
以一个bean类为例:
package com.example;
public class User {
private String id;
private String name;
private Integer age;
private Integer grade;
// ... ignore getter and setter
// override its toString method
@Override
public String toString() {
return "User{" +
"id='" + id + ''' +
", name='" + name + ''' +
", age=" + age +
", grade=" + grade +
'}';
}
}
在MongoDB数据库中新建一个collection(也就是表),名字叫user,插入几条数据,比如:
![14c725507dd09cd317fda6b5c5f009db.png](https://i-blog.csdnimg.cn/blog_migrate/7077090f7c7f708f97f2a388ce930298.jpeg)
注:这里用的可视化工具是robo 3t:https://robomongo.org/
我们这里先默认JavaBean的字段与user表的字段名保持一致。
下面我们编写测试类:
@SpringBootTest
@RunWith(SpringRunner.class)
public class MongoTest {
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void test1() {
List<User> userList = mongoTemplate.findAll(User.class);
if (userList != null && userList.size() > 0) {
userList.forEach(user -> {
System.out.println(user.toString());
});
}
}
}
运行测试类,输出如下:
User{id='5d243534514701183f5fcab8', name='zf0', age=12, grade=1}
User{id='5d243534514701183f5fcab9', name='zf1', age=13, grade=2}
User{id='5d243534514701183f5fcaba', name='zf2', age=14, grade=3}
User{id='5d243534514701183f5fcabb', name='zf3', age=15, grade=4}
User{id='5d243534514701183f5fcabc', name='zf4', age=16, grade=5}
二、基于SpringBoot的MongoDB增删改查操作
下面来实现一个基于SpringBoot的对MongoDB增删改查操作的简单示例,依然使用上面的环境:
maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
yml:
server:
port: 8866
spring:
data:
mongodb:
uri: "mongodb://localhost:27017/test"
User类:
这里我们清楚一下之前的数据,把mongo里的user表里的数据全部删掉。
![f1ed47d1de7bd03f0996c4e8c2f0712a.png](https://i-blog.csdnimg.cn/blog_migrate/9912a43f1b33220346d11d2d7e98806d.png)
注:这里用的可视化工具admin-mongo:
新建一个不同的user类:
@Document("user")
public class User {
@Id
private String id;
@Field("name")
private String name;
@Field("password")
private String password;
@Field("address")
private String address;
@Field("create_time")
private Date createTime;
@Field("last_update_time")
private Date lastUpdateTime;
// ... ignore getter and setter methods
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
此处定义一个JsonResult类,用于封装接口返回数据:
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JsonResult {
/**
* 未登录
*/
public static final int NO_LOGIN = 400;
/**
* 登录失败
*/
public static final int LOGIN_FAILED = 401;
/**
* TOKEN过期
*/
public static final int TOKEN_EXPIRED = 402;
/**
* 无权限
*/
public static final int NO_PERMISSION = 403;
private Boolean success;
private Integer code;
private String msg;
private Object data;
public JsonResult(Boolean success) {
this.success = success;
}
public JsonResult(Boolean success, String msg) {
this.success = success;
this.msg = msg;
}
public JsonResult(Integer code, Boolean success, String msg) {
this.code = code;
this.success = success;
this.msg = msg;
}
public JsonResult(Boolean success, Object data) {
this.success = success;
this.data = data;
}
public JsonResult(Boolean success, Integer code, String msg, Object data) {
this.success = success;
this.code = code;
this.msg = msg;
this.data = data;
}
// ... ignore getter and setter methods
public void put(String key, Object value) {
if (data == null) {
data = new HashMap<>();
}
((Map) data).put(key, value);
}
public void putAll(Map<String, Object> map) {
if (data == null) {
data = new HashMap<>();
}
((Map) data).putAll(map);
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
下面编写测试接口类,实现用户的新增、删除、更新、查询功能
UserController类:
@RestController
@RequestMapping(value = "user")
public class UserController {
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping(value = "")
public JsonResult list() {
List<User> userList = mongoTemplate.findAll(User.class, "user");
return new JsonResult(true, userList);
}
@PostMapping(value = "")
public JsonResult add(User user) {
String msg = verifySaveForm(user);
if (!StringUtils.isEmpty(msg)) {
return new JsonResult(false, msg);
}
if (user.getId() == null) {
user.setCreateTime(new Date());
user.setLastUpdateTime(new Date());
User newUser = mongoTemplate.insert(user, "user");
return new JsonResult(true, newUser);
} else {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name", user.getName());
update.set("password", user.getPassword());
update.set("address", user.getAddress());
update.set("last_update_time", new Date());
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "user");
return new JsonResult(true, updateResult);
}
}
@DeleteMapping(value = "{id}")
public JsonResult delete(@PathVariable String id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
DeleteResult deleteResult = mongoTemplate.remove(query, User.class, "user");
return new JsonResult(true, deleteResult);
}
// private methods
private String verifySaveForm(User user) {
if (user == null || StringUtils.isEmpty(user.getName())) {
return "用户名不能为空";
} else if (user.getPassword() == null) {
return "密码不能为空";
}
return null;
}
}
下面用postman模拟一下请求:
新增用户:
![6aacf6b5c1929ca3691f68caf7e00120.png](https://i-blog.csdnimg.cn/blog_migrate/4d2e51f9fa63354927f73cff30137c7f.png)
查看Mongodb:
![0de09542650175c217140da4a1ee1ced.png](https://i-blog.csdnimg.cn/blog_migrate/7e2f35a89af4f0394d5f8943b04f7422.png)
更改数据,新增多个用户:
![435201ac3b1bd788c5e488eea0eba5be.png](https://i-blog.csdnimg.cn/blog_migrate/ce044dd014720dafb60eb28d9c345cfb.jpeg)
列表查询:
![10d3496a8fbf9ae0e334af5e6b1b9e2a.png](https://i-blog.csdnimg.cn/blog_migrate/27cd721986540e8ea5c2856207e3a98e.jpeg)
更改user:
![7f7a177a019fd100184108f7b9235ca8.png](https://i-blog.csdnimg.cn/blog_migrate/28c786f334113f8e067794df24416b2a.png)
![e99de8936d90f88a7d84fb170ab24b52.png](https://i-blog.csdnimg.cn/blog_migrate/b16ac95e6614700666d030dfb7b41510.jpeg)
删除user:
![377eb9e528b66ad3722292bd3cd3bc37.png](https://i-blog.csdnimg.cn/blog_migrate/c000b182f93f23c41029099bb5eb7c8f.png)
![bead0f2001577093ebb75bacbf5ea2d6.png](https://i-blog.csdnimg.cn/blog_migrate/48782bc9b22b37a2c231a0b2d6de854f.jpeg)
好,到此为止,我们已经在SpringBoot项目中引入了MongoDB,并实现了基本的增删改查操作,这将是我们使用MongoDB开发更加复杂的业务的基础!
交流学习
我的个人网站:http://www.eknown.cn
Git仓库地址:https://github.com/laolunsi
另外也欢迎大家关注我的公众号:猿生物语,一起学习Java/SpringBoot/SpringCloud技术。
![3b98ba3d18cc986754719c1f9427763d.png](https://i-blog.csdnimg.cn/blog_migrate/ceea9fbff67a89cf014936078daf2322.jpeg)