【发布时间】:2013-09-24 08:29:05
【问题描述】:
我有以下代码。它工作正常。没有例外等。我正在循环使用标准查询检索到的 JPA 实体对象列表(因此列表中没有任何 null 对象)。
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 语句中添加了一条语句,这样只有在循环列表中的对象具有contractManagerID 或0 时才会触发一行。标记如下;
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 语句它也无法工作,但没有它它也能正常工作。我完全迷路了。
【问题讨论】:
-
getContractManagerID()返回什么? -
您确定
periodical.getContractManagerID()本身不为空吗? -
getContractManagerID()返回一个整数。数据库中没有空值,但即使有if语句也不会被满足,它肯定会继续吗? -
@Rudi Kershaw;它很可能返回一个整数,但一个整数可以为空。 (参见 int)。你需要检查一下。
标签: java exception jpa if-statement nullpointerexception