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

jav*_*900 2 java repository mongodb spring-mongodb spring-repositories

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

}
Run Code Online (Sandbox Code Playgroud)

我有以下内容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);

}
Run Code Online (Sandbox Code Playgroud)

在我的服务类中,我有一个工作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"?

}
Run Code Online (Sandbox Code Playgroud)

我对 比较陌生MongoDB,有固定的方法可以做到这一点吗?即保持相同的ObjectId等但更新文档中的其他字段?

var*_*man 8

注意:以下代码未经测试,但它给了你一个很好的想法。有两种情况。

  1. 如果您不随请求发送 ID,数据将被插入。
  2. 如果您随请求发送现有 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

存储库

interface RoundRepository extends MongoRepository<Round, ObjectId> {
}
Run Code Online (Sandbox Code Playgroud)

服务

interface RoundService {
    Round save(Round round);
}
Run Code Online (Sandbox Code Playgroud)

服务实施

@Service
public RoundServiceImpl implements RoundService{
    @Autowired
    RoundRepository repository;

    @Override
    public Round save(Round round){
        repository.save(round);
    }
}
Run Code Online (Sandbox Code Playgroud)

您不需要实际执行特殊查询。但如果你需要做一些逻辑。

@Override
public Round save(Round round){

    if(round.get_id()!=null){
        //update logic
    }else {
        // insert logic
    }

    repository.save(round);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以将注释@Query@Update一起使用。

使用@Queryfind部分和@Update使用德$set部分。

例子

public interface RoundRepository extends MongoRepository<Round, String> {

    @Query("{'userId' : ?0}")
    @Update("{'$set': {'round': ?1}}")
    Integer updateRound(String id, Round updatedRound);
}
Run Code Online (Sandbox Code Playgroud)

参考: https: //docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.update