Objectify 并不总是 return 结果

Objectify doesn't always return results

我正在使用 Objectify 将数据存储在 Google App Engine 的数据存储上。我一直在尝试实现两个 class 之间的一对多关系,但是通过存储参数化键列表。下面的方法有时工作得很好,但有时 return 是一个空数组 - 有人知道为什么会这样吗?

它将 return 正确的 CourseYears 列表,或者

{
 "items": [
 ]
}

方法如下:

@ApiMethod(name = "getCourseYears") @ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public ArrayList<CourseYear> getCourseYears(@Named("name") String name){

    Course course = ofy().load().type(Course.class).filter("name", name).first().now();
    System.out.println(course.getName());

    ArrayList<CourseYear> courseYears = new ArrayList<CourseYear>();
    for(Key<CourseYear> courseYearKey: course.getCourseYears()){
        courseYears.add(ofy().load().type(CourseYear.class).id(courseYearKey.getId()).now());
    }

    return courseYears;
}

存储许多 CourseYear 键的课程 class

@Entity
public class Course {
@Id
@Index
private Long courseId;

private String code;

@Index
private String name;

@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public List<Key<CourseYear>> getCourseYears() {
    return courseYears;
}

@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public void setCourseYears(List<Key<CourseYear>> courseYears) {
    this.courseYears = courseYears;
} 

@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
     public void addCourseYear(Key<CourseYear> courseYearRef){
    courseYears.add(courseYearRef);
}
@Load
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
List<Key<CourseYear>> courseYears = new ArrayList<Key<CourseYear>>();

...

}

我正在调试服务器上使用 API 资源管理器对此进行调试。我发现它通常会在开始时工作几次,但如果我离开并 return 到 API 并再次尝试 运行 它,它不会在之后再次开始工作那。

有谁知道可能出了什么问题吗?

非常感谢。

您可能希望减少发送到数据存储区的查询数量。尝试这样的事情:

Course course = ofy().load().type(Course.class).filter("name", name).first().now();

ArrayList<CourseYear> courseYears = new ArrayList<CourseYear>();
List<Long> courseIds = new List<>();
for(Key<CourseYear> courseYearKey: course.getCourseYears()){
    courseIds.add(courseYearKey.getId());
}
Map<Long, Course> courses = ofy().load().type(CourseYear.class).ids(courseIds).list();
// add all courses from map to you courseYears list

我还强烈建议更改您的数据结构/实体:

在您的 CourseYears 中为父课程添加 属性 Ref<Course> courseRef 并将其编入索引 (@Index)。然后通过

查询
ofy().load().type(CourseYear.class).filter("courseRef", yourCourseRef).list();

这样您只需要一个查询。

两个最有可能的候选人是:

  1. 高复制数据存储的最终一致性行为。查询(即您的 filter() 操作)总是 运行 有点落后,因为索引通过 GAE 异步传播。请参阅 GAE 文档。
  2. 您还没有安装 ObjectifyFilter。阅读设置指南。如果您尚未安装 Objectify 的最新版本,则会抛出错误,因此如果您使用的是最新版本,则不是这样。