NullPointerException尝试获取Google App Engine中实体中字段的值时出现异常

时间:2016-11-14 10:22:33

标签: java google-app-engine google-cloud-platform google-cloud-datastore objectify

我有一个学生实体,其中有一个字段,这是对像这样的部门实体的引用。          { id: '<as specified in doc definition>', headlineLevel: '<as specified in doc definition>', text: '<as specified in doc definition>', ul: '<as specified in doc definition>', ol: '<as specified in doc definition>', table: '<as specified in doc definition>', image: '<as specified in doc definition>', qr: '<as specified in doc definition>', canvas: '<as specified in doc definition>', columns: '<as specified in doc definition>', style: '<as specified in doc definition>', pageOrientation '<as specified in doc definition>', pageNumbers: [2, 3], // The pages this element is visible on (e.g. multi-line text could be on more than one page) pages: 6, // the total number of pages of this document stack: false, // if this is an element which encapsulates multiple sub-objects startPosition: { pageNumber: 2, // the page this node starts on pageOrientation: 'landscape', // the orientation of this page left: 60, // the left position right: 60, // the right position verticalRatio: 0.2, // the ratio of space used vertically in this document (excluding margins) horizontalRatio: 0.0 // the ratio of space used horizontally in this document (excluding margins) } }
   那么Department字段的getter和setter如下所示

@Load  private @Index Ref<Department> department;

学生实体中还有一个字段,其中包含对SchoolFaculty Entity的引用

 public Department getDepartment() {
    return department.get();
}

public void setDepartment(Key<Department> department) {
    this.department = Ref.create(department);
}

它有以下getter和setter

@Load
private @Index Ref<SchoolFaculty> schoolFaculty;

部门实体又有一个字段,其中包含一个教师实体的密钥,如下所示

  public SchoolFaculty getSchoolFaculty() {
      if (schoolFaculty != null) 
           return schoolFaculty.get();
 return null;     
}

public void setSchoolFaculty(Key<SchoolFaculty> schoolFaculty) { 
    this.schoolFaculty = Ref.create(schoolFaculty); 
}

该字段的getter和setter如下所示

@Index
private Key<SchoolFaculty> schoolFaculty;

我使用Google Api Explorer在本地数据存储区中创建了一个部门和SchoolFaculty实体,该部门将其SchoolFaculty参考设置为有效值,该值也存在于SchoolFaculty表中,即该部门有一个教员,但是当我尝试使用以下代码设置学生的SchoolFaculty时,我得到一个NullPointerException。这是代码

 public String getSchoolFaculty() {
    return schoolFaculty.toWebSafeString();
}


public void setSchoolFaculty(Key<SchoolFaculty> schoolFaculty) {
    this.schoolFaculty = schoolFaculty;
}

我正在使用objectify进行数据存储区事务,并且添加了对objectify依赖项的所有引用。

1 个答案:

答案 0 :(得分:1)

因为student.getDepartment().getSchoolFaculty()在触发条件语句之前抛出空指针,并且google appengine键无法为null实体或websafestring创建键。因此,请仔细调试并检查getDepartment()是否返回null或首先返回的内容,如果要使用Key创建数据存储的键的空字段,则使用默认例如

Key.create(SchoolFaculty.class, "default"); // when it is null

希望这很有用