【问题标题】:How to update an element in spring boot using save method?如何使用保存方法更新 Spring Boot 中的元素?
【发布时间】:2020-07-17 09:52:31
【问题描述】:

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

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

这是我的 PRepository:

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

【问题讨论】:

    标签: java spring-boot model-view-controller spring-data


    【解决方案1】:

    您从未设置过 copyOfExistingR 的 id。

    【讨论】:

    • 我只是尝试直接设置id(setId(“something”),但不幸的是,它没有帮助。不过,当前的问题是关于“/editData”,我刚刚检查了我的“/addData”,我也没有添加任何id。所以,我认为id是自动添加的。不是吗?
    【解决方案2】:

    解决方法是你只需设置'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 ;
        }
    

    【讨论】:

    • 我试过了,但没有用。我在您在评论中提到的位置(就在开头)添加了 id。
    • 首先检查'pFound'是否为空。请分享您修改后的代码。
    • 感谢您的跟进。我使用“copyOfCurrentReview.setId("something");”并且“pFound”不为空。仅供参考,我在为 /addData 编写代码时遇到了完全相同的问题,当时问题已由stackoverflow.com/questions/51943411/… 解决,但这一次,p 类的实例存在,我无法执行相同的过程。我认为我的代码逻辑有问题。我使用元素的副本而不是直接在数据库上工作可以吗?
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      相关资源
      最近更新 更多