我有以下架构,使用 Objectify
@Entity
public class Book{
@Id
private long id;
private Key<Page> pages;
…
}
@Entity
public class Page{
@Id
private String id;
…
public Page(Book book,int pageNumber){
this.id = book.getId()+””+pageNumber;
…
}
}
我收到投诉
com.googlecode.objectify.LoadException: Error loading Book(1401058017250)/Page("14010580172505639445604728832"): Loaded Entity has parent but com.company.api.db.Page has no @Parent
Caused by: java.lang.IllegalStateException: Loaded Entity has parent but com.company.api.db.Page has no @Parent
我来自 Eclipse 和 Datanucleus,在该框架中代码是
@Entity
public class Book{
@Id
private long id;
private List<Page> pages;
…
}
@Entity
public class Page{
@Id
private Key key;
…
public Page(Book book,int pageNumber){
this.key = createKey(book.getId(),pageNumber);
…
}
private Key createKey(long bookId, long pageNumber) {
Key bookKey = KeyFactory.createKey(Book.class.getSimpleName(), bookId);
Key key = KeyFactory.createKey(bookKey, Page.class.getSimpleName(), bookId + "" + pageNumber);
return key;
}
}
无论它是否是最好的代码,它过去都是有效的。所以无论如何,我正在迁移到 Objectify 和 Android Studio。如何重写此架构以避免出现错误?如果有人知道答案,请复制并粘贴我的代码片段并进行适当的编辑。
最佳答案
在旧代码中,您将 bookKey 标记为父实体。在新代码中,您需要:
@Parent
Key<Book> parentBook;
您的新类(class)应该是:
@Entity
public class Book{
@Id
private long id;
private List<Key<Page>> pages;
…
}
@Entity
public class Page{
@Id
private String id;
@Parent
Key<Book> parentBook;
…
public Page(long bookId, int pageNumber){
this.id = bookId + ”” +pageNumber;
this.parentBook = Key.create(Book.class, bookId);
…
}
}
在此处了解有关键和对象化的更多信息:https://code.google.com/p/objectify-appengine/wiki/Concepts#Keys
关于java - 加载的实体有父级但没有@Parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867063/