繁体   English   中英

MongoDB 和 Spring 引导 - 更新文档的最佳方式?

[英]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等,但更新文档中的其他字段?

注意:以下代码未经测试,但它可以很好地为您提供一个思路。 有两种情况。

  1. 如果您没有随请求发送 id,则将插入数据。
  2. 如果您在请求中发送现有 ID,则数据将被更新。

注解@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM