java - MongoDB 和 Spring Boot - 更新文档的最佳方式?
问题描述
Java POJO
我的Spring Boot 应用程序中有以下内容:
public class Round {
private ObjectId _id;
@NotEmpty
@Getter
@Setter
@Accessors(fluent = true)
@JsonProperty("userId")
private String userId;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
@Getter
@Setter
@Accessors(fluent = true)
@JsonProperty("date")
private LocalDate date;
@Min(value = 1, message = "Score should not be less than 1")
@Getter
@Setter
@Accessors(fluent = true)
@JsonProperty("score")
private int score;
// rest of fields
}
我有以下内容MongoRepository
:
@Repository
public interface RoundRepository extends MongoRepository<Round, String> {
List<Round> findByUserId(String userId);
@Query("{'userId' : ?0 , '_id' : ?1}")
Optional<Round> findByUserIdAnd_id(String userId, ObjectId _id);
}
在我的 Service 类中,我有一个工作create()
,我正在尝试实现一个update()
方法来与PUT
我的控制器中的映射一起使用:
public Round create(String userId, @Valid @NotNull @RequestBody Round round) {
// set userId from path
round.userId(userId);
roundRepository.save(round);
return round;
}
public void put(String userId, ObjectId objectId, Round updatedRound) {
// get original round
Optional<Round> round = roundRepository.findByUserIdAnd_id(userId, objectId);
//todo - how to implement PUT in mongo to update to "updatedRound"?
}
我比较陌生MongoDB
,有没有固定的方法来做到这一点?即保持相同ObjectId
等但更新文档中的其他字段?
解决方案
注意:以下代码未经测试,但可以很好地为您提供一个思路。有两种情况。
- 如果您没有随请求发送 id,则将插入数据。
- 如果您在请求中发送现有 ID,则数据将被更新。
@Id private ObjectId _id;
在您的实体类中注释
控制器
@RestController
@RequestMapping("YOUR_URL")
public class RoundController{
@PostMapping("YOUR_URL")
public ResponseEntity<Round> update(@Valid @RequestBody Round updateRound, BindingResult result){
//Bindning Error handle
if (bindingResult.hasErrors()) {
List<String> errors = new ArrayList<>();
for (ObjectError res : bindingResult.getFieldErrors()) {
errors.add(res.getDefaultMessage());
}
throw new RuntimeError(errors.toString());
}
return new ResponseEntity<>(roundService.save(updateRound), HttpStatus.OK);
}
}
存储库
interface RoundRepository extends MongoRepository<Round, ObjectId> {
}
服务
interface RoundService {
Round save(Round round);
}
服务实施
@Service
public RoundServiceImpl implements RoundService{
@Autowired
RoundRepository repository;
@Override
public Round save(Round round){
repository.save(round);
}
}
您不需要实际执行特殊查询。但是如果你需要做一些逻辑。
@Override
public Round save(Round round){
if(round.get_id()!=null){
//update logic
}else {
// insert logic
}
repository.save(round);
}
推荐阅读
- java - 如何在 Eclipse 中调试 WAR,而不是远程调试?
- c - c arduino 按钮中断(isr),使多个 LED 点亮和熄灭
- php - Laravel - GuzzleHttp:握手失败
- java - 我的代码中有什么问题?它没有编译并得到错误。请帮助我
- .net - 订阅 Angular 中的 json 文件
- python - Selenium 无法找到元素,即使在给出了很高的隐式等待时间之后
- xslt - XSL FO 有时会返回主题标签而不是所需的 unicode 字符
- php - PHP 和 MySQL:只比较月份和日期,而不考虑日期字段中的年份
- javascript - 带有 JEST 的 Nodejs 如何使用 ES6 和相对路径导入?
- django - django 的 bulk_create 是原子的吗?