2013-09-24 25 views
1

我有以下代码。它工作正常。没有例外等。我正在循环使用标准查询检索的JPA实体对象列表(因此列表中没有任何null对象)。Mysterious NullPointerException

for (PeriodicalTable periodical : resultsP){ 
     stringFor.add(periodical.getReference()); 
     site = em.find(SiteTable.class, periodical.getSiteID()); 
     if (site != null && site.getPostcode() != null && !site.getPostcode().equals("")){ 
      tempString = site.getPostcode().replaceAll("\\s+", " "); 
      periodical.setPostcode(tempString.trim());      
      }  
     } 

现在,我已经在if声明中,这样,如果在列表中绕环对象具有的0一个contractManagerID一行仅触发。标记如下;

for (PeriodicalTable periodical : resultsP){ 
     if(periodical.getContractManagerID()==0) //<---- HERE!!!! 
     { 
      stringFor.add(periodical.getReference()); 
     } 
     site = em.find(SiteTable.class, periodical.getSiteID());   
     if (site != null && site.getPostcode() != null && !site.getPostcode().equals("")){ 
      tempString = site.getPostcode().replaceAll("\\s+", " "); 
      periodical.setPostcode(tempString.trim());      
      }     
     } 

一些调试后,我已经分离出的异常,因为从if语句本身来(标有“HERE”),但我不知道怎么说都可以。我们知道列表中没有null对象,因为否则即使没有if语句也不行,但没有它就可以正常工作。我完全失去了。

+0

getContractManagerID()返回什么? –

+1

你确定'periodical.getContractManagerID()'本身不是null吗? – Bathsheba

+0

'getContractManagerID()'返回一个整数。数据库中没有空值,但即使if语句不满足,它肯定会继续? –

回答

4

只有这里的可能性是periodical.getContractManagerID()正在返回null

比较null == 0会给你一个NullPointerException

而是执行此操作:

if (periodical.getContractManagerID() == null || 
    periodical.getContractManagerID() == 0) 
+0

尝试过它,它的工作原理。谢谢。但它确实提出了一个问题。如果SQL表对所有的ContractManagerID有0个值,为什么它会返回0和一些空值,而不是全部? –

+0

@Rudi Kershaw:也许这就是数据库视图表示空值的方式。 – Bathsheba

+0

可能,我想......但是在Netbeans的数据库中还有其他空值可见。猜猜这一点将不得不保持一个谜。 –

1

有发现了一个相当简单的方法:

  • 坐落在这里线断点。当Eclipse(我假设你使用Eclipse)调试器弹出时,选择periodical变量并按Ctrl + Shift + I(这称为“检查”)。如果不为零,则评估periodical.getContractManagerID()。它应该是null

这意味着您没有使用原语来存储该号码。您应该使用原语,添加合理的默认值或检查null

如果您在PeriodicalTable类中有Integer,那意味着它可以是null