[英]MongoDB and Spring Boot - Best way to update a Document?
我的 spring 启动应用程序中有以下Java POJO
:
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);
}
在我的服务 class 中,我有一个有效的create()
,我正在尝试实现一个update()
方法,以便在我的 controller 中与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 private ObjectId _id;
在您的实体 class
Controller
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.