如何使用save方法更新spring-boot中的元素



我有两个类,它们包含以下元素:

@Document(collection = "ClassP")
Class P{
@Id
private String p_id;
}
@Document(collection = "ClassR")
Class R{
@Id
private String r_id;
private String item;
@DBRef
private P p;
@DBRef
private User user;
}

这是我的简历:

public interface PMongoRepository extends CrudRepository<P, String>{
P findPById(String p_id);
}

我要做的是从类R更新item。我从前端获得更改后的项目,在我的控制器中我有新的项目。因此,从前端侧看没有问题。在我的控制器中,我有以下代码:

@RequestMapping(value = "/editData", method = RequestMethod.POST, consumes = "application/json")
public ModelAndView editData(@RequestBody Map<String, String> new_items) {
ModelAndView modelAndView = new ModelAndView();
R copyOfExistingR= new R();
P pFound = pRepository.findPById(new_items.get("p_id"));
copyOfExistingR.setP(pFound);
copyOfExistingR.setItem(new_items.get("sep"));
copyOfExistingR.setUser(user);
rRepository.save(copyOfExistingR);
return modelAndView ;
}

但代码并没有按预期工作。在rRepository.save(copyOfExistingR);上,我得到以下错误:

Cannot create a reference to an object with a NULL id.

pFound不是null,我可以打印出来,但我不知道更新R类有什么错。如果有人能帮助我,我将不胜感激。

您从未设置copyOfExistingR的id。

解决方案是只设置'r_id'

@RequestMapping(value = "/editData", method = RequestMethod.POST, consumes = "application/json")
public ModelAndView editData(@RequestBody Map<String, String> new_items) {
ModelAndView modelAndView = new ModelAndView();
R copyOfExistingR = new R();
//-----Here you set your r_id for object copyOfExistingR----
P pFound = pRepository.findPById(new_items.get("p_id"));
copyOfExistingR.setP(pFound);
copyOfExistingR.setItem(new_items.get("sep"));
copyOfExistingR.setUser(user);
rRepository.save(copyOfExistingR);
return modelAndView ;
}

问题是我在p类中定义了一个高于@Id的变量,这是有问题的。@Id必须始终是类中的第一个项。

最新更新