我正在尝试重构我的一些数据模型,但我遇到了一个我不明白的问题。
最初我有一个由3个实体类组成的简单数据模型,看起来像这样:
@Entity
public final class Teacher {
@Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
@Entity
public final class Student {
@Id
private String username;
@Load
@Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
@Entity
public final class School {
@Id
private String name;
@Load
private Set<Ref<Teacher>> teachers;
@Load
private Set<Ref<Student>> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
这一切都很好。
但是我们决定直接嵌入实体而不是Refs ...
会更有用@Entity
@Embed
public final class Teacher {
@Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
@Entity
@Embed
public final class Student {
@Id
private String username;
@Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
@Entity
public final class School {
@Id
private String name;
private Set<Teacher> teachers;
private Set<Student> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
在进行这些更改之后,在我们的测试设置方法中注册School类期间,所有的junit测试都开始失败并出现AssertionError,如下所示:
@Before
public void setUp() throws Exception {
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(Teacher.class);
ObjectifyService.register(Student.class);
ObjectifyService.register(School.class);
// more setup
}
AssertionError不会出现,直到注册School类的行,并且根据方法抛出堆栈跟踪&#34; com.googlecode.objectify.impl.translate.CreateContext.enterCollection&#34;但我不确定如何修复它。
有没有人有任何想法?
答案 0 :(得分:0)
我怀疑你得到的错误是因为你正在尝试注册一个你用@Embed注释的类。
客观化文档明确指出@Embed类不必注册 - 也许这就是问题的原因。
另外,我对此并不是100%肯定,但我认为你在嵌入式课程中不需要@Id。
我建议您进行以下更改:
@Embed
public final class Teacher {
@Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
@Embed
public final class Student {
@Id
private String username;
@Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
@Before
public void setUp() throws Exception
{
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(School.class);
// more setup
}
希望这有帮助!