I have two classes which have the following elements:
@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;
}
Here is my PRepository:
public interface PMongoRepository extends CrudRepository<P, String>{
P findPById(String p_id);
}
What I am going to do is to update the item
from class R. I get the changed item from the frontend and in my controller I have the new item. So, there is no problem from the front end side. In my controller, I have the following code:
@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 ;
}
But the code doesn't work as expected. On the rRepository.save(copyOfExistingR);
I get the following error:
Cannot create a reference to an object with a NULL id.
The pFound
is not null and I can print it out, but I don't know what I am doing wrong with updating the R class. I would be thankful if anybody could help me.
You never set id of copyOfExistingR.
The solution is that you just set the '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 ;
}
The problem was that I had defined a variable above @Id in the P class and it was problematic. The @Id must always be the first item in the class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.