该篇介绍MongoDB更新以及删除操作。
代码
添加服务代码:
> vim src/main/java/com/example/mymongodb/MongoService2.java
package com.example.mymongodb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
/**
* @author by Remer
* @date on 2020-12-23
*/
@Service
public class MongoService2 {
private MongoTemplate mongoTemplate;
@Autowired
public MongoService2(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public Machine findOne(String machineName) {
Query query = query(where("machineName").is(machineName));
Machine machine = mongoTemplate.findOne(query, Machine.class);
return machine;
}
public Machine save(Machine machine) {
return mongoTemplate.save(machine);
}
public String delete(Machine machine) {
mongoTemplate.remove(machine);
return "success";
}
}
添加控制器代码:
> vim src/main/java/com/example/mymongodb/MongoController2.java
package com.example.mymongodb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author by Remer
* @date on 2020-12-23
*/
@RestController
public class MongoController2 {
private MongoService2 mongoService;
@Autowired
public MongoController2(MongoService2 mongoService) {
this.mongoService = mongoService;
}
@PostMapping("/machines/{machineName}")
public Machine update(@PathVariable String machineName) {
Machine machine = mongoService.findOne(machineName);
machine.setMachineName("更新机械名字");
machine.setFenceName("更新围栏名字");
return mongoService.save(machine);
}
@GetMapping("/machines/{machineName}")
public Machine detail(@PathVariable String machineName) {
return mongoService.findOne(machineName);
}
@DeleteMapping("/machines/{machineName}")
public String delete(@PathVariable String machineName) {
Machine machine = mongoService.findOne(machineName);
return mongoService.delete(machine);
}
}
单条查询
执行请求:
(GET) http://localhost:8082/machines/测试机械1
返回结果:
{
"id": "5fe31e00370f2869d94f5489",
"machineName": "测试机械1",
"fenceName": "测试机械围栏1",
"remark": "测试机械备注1"
}
单条编辑
(POST) http://localhost:8082/machines/测试机械1
返回结果:
{
"id": "5fe31e00370f2869d94f5489",
"machineName": "更新机械名字",
"fenceName": "更新围栏名字",
"remark": "测试机械备注1"
}
单条删除
(DELETE) http://localhost:8082/machines/测试机械1
返回结果:
success
查询结果:
(GET) http://localhost:8082/machines/测试机械1
null
网友评论