gpt4 book ai didi

java - 如何使用 save 方法更新 Spring Boot 中的元素?

转载 作者:行者123 更新时间:2023-12-01 17:35:54 27 4
gpt4 key购买 nike

我有两个具有以下元素的类:

@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);
}

我要做的是更新item我从前端获取更改后的项目,并在我的 Controller 中获得新项目。所以,从前端方面来说是没有问题的。在我的 Controller 中,我有以下代码:

@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不为空,我可以将其打印出来,但我不知道更新 R 类时我做错了什么。如果有人能帮助我,我将不胜感激。

最佳答案

您从未设置 copyOfExistingR 的 id。

关于java - 如何使用 save 方法更新 Spring Boot 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61042185/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com