我有以下带有 Spring Web
框架的简单 Java
Controller :
@RestController
@RequestMapping("/rounds")
@Slf4j
public class RoundController {
private RoundService roundService;
@Autowired
public RoundController(RoundService roundService) {
this.roundService = roundService;
}
@GetMapping(
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<Round> find() {
return roundService.find();
}
@GetMapping(
path = "/{userId}",
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<Round> get(@PathVariable String userId) {
return roundService.getRoundsByUserId(userId);
}
@PostMapping(
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
public Round create(@Valid @NotNull @RequestBody Round round) {
roundService.create(round);
return round;
}
@DeleteMapping(
path = "/{id}",
produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable String id) {
ObjectId objectId = new ObjectId(id);
roundService.delete(objectId);
}
}
使用 Mongo
时是否有对对象进行更新/修补的最佳实践?
最好只使用 POST
方法,并使用用户所做的更改将 Round 对象重新保存在数据库中吗?
最佳答案
据我所知,最佳实践不应该是使用 POST 进行更新/修补。
保持 POST 只进行回合创建。
如果您使用 spring data mongodb,只需使用您的实体调用存储库的 save 方法 请参阅https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/repository/MongoRepository.html
对于更新,最好在 Controller 中添加 PUT/{roundId} 以及:
- 如果您拥有所有回合数据,请调用您的保存方法
- 调用 findById 获取完整数据并设置要更改的数据,然后保存(但这更像是 PATCH)
或者您也可以添加 PATCH/{roundId} 并仅更新文档中所需的字段 请参阅https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html
关于java - MongoDB 和 Spring MVC : PATCH operation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067178/