首页 > 解决方案 > java.lang.NullPointerException: null - 调用 getAttributes().contains(key) 时

问题描述

我在尝试调用 getter 时得到了 NPE。它是一个 @OneToMany 映射属性。当我通过当前对象以外的其他方式调用时,它可以工作。

它不适用于以下代码。

@PostMapping("/updateservice")
    public void updateService(@ModelAttribute ServiceTyping serviceTyping, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse res) throws IOException {

if(serviceTyping.getServiceEntryAttributes().containsKey(ServiceConstants.outsourcer)) {
            LOG.info("**INFO OUTSOURCER FOUND*******");
        }
}

但是当我从其他对象访问时工作

@PostMapping("/updateservice")
    public void updateService(@ModelAttribute ServiceTyping serviceTyping, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse res) throws IOException {

ServiceTyping st = entryService.findTypingEntryById((long) 194);


if(st.getServiceEntryAttributes().containsKey(ServiceConstants.outsourcer)) {
            LOG.info("**INFO OUTSOURCER FOUND*******");
        }
}

我尝试在代码下面进行热编码,我的意思是直接传递当前对象的 id。它也不起作用。

@PostMapping("/updateservice")
    public void updateService(@ModelAttribute ServiceTyping serviceTyping, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse res) throws IOException {

//here 176 is the id of the entity
ServiceTyping st = entryService.findTypingEntryById((long) 176);

    //checking the object which has the 176 is found are not
    if(entryService.findEntryById((long) 176)!=null) {
            LOG.info("**INFO OBJECT FOUND*******");
           if(entryService.findEntryById((long) 176).getServiceEntryAttributes().containsKey(ServiceConstants.outsourcer)) {
         LOG.info("**INFO OUTSOURCER FOUND*******"); }

    }


}

在此处输入图像描述 我并不是说它不适用于特定的 id 176。它不适用于任何其他对象。但它适用于当我通过在中找到的相同对象以外的对象访问public void updateService(@ModelAttribute ServiceTyping serviceTyping)

从代码和附表中,我已经证明了两件事。1)我尝试访问的对象不为空;2)找到我试图获取的值,它也不为空。

如果我感到困惑,请告诉我

标签: javaspringspring-bootspring-mvcspring-data-jpa

解决方案


推荐阅读