SpringBoot整合MongoDB的示例
本节使用SpringBoot 2.1.9.RELEASE,示例源码在https://github.com/laolunsi/spring-boot-examples/tree/master/06-spring-boot-mongo-demo
SpringBoot可以非常方便地引入和操作MongoDB。本节分两部分,记录个人学习SpringBoot使用MongoDB数据库的一些知识。
第一部分是一个简单的springboot连接mongo的demo,测试查询功能。
第二部分是基于mongo实现的增删改查数据示例。
本节使用SpringBoot 2.1.9.RELEASE
一、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,插入几条数据,比如:
注:这里用的可视化工具是robo 3t:https://www.jb51.net/database/567493.html
我们这里先默认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表里的数据全部删掉。
注:这里用的可视化工具admin-mongo:https://github.com/mrvautin/adminMongo
新建一个不同的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模拟一下请求:
新增用户:
查看Mongodb:
更改数据,新增多个用户:
列表查询:
更改user:
删除user:
以上就是SpringBoot整合MongoDB的示例的详细内容,更多关于SpringBoot整合MongoDB的资料请关注我们其它相关文章!