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()
方法以与我的控制器中的 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
比较陌生,有固定的方法吗? IE。保持相同 ObjectId
等但更新文档中的其他字段?
注意:以下代码没有经过测试,但它给了你一个很好的思路。
有两种情况。
- 如果您不在请求中发送 ID,数据将会
已插入。
- 如果您在请求中发送现有 ID,数据将
已更新。
在您的实体中注释 @Id private ObjectId _id;
class
控制器
@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);
}
我的 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()
方法以与我的控制器中的 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
比较陌生,有固定的方法吗? IE。保持相同 ObjectId
等但更新文档中的其他字段?
注意:以下代码没有经过测试,但它给了你一个很好的思路。 有两种情况。
- 如果您不在请求中发送 ID,数据将会 已插入。
- 如果您在请求中发送现有 ID,数据将 已更新。
在您的实体中注释 @Id private ObjectId _id;
class
控制器
@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);
}