我有这个简单的模型:
@Table(name = "Books")
public class Book extends Model {
@Column(name = "title")
String title;
//Variable to cache the pages
List<Page> pages;
public Book(){
}
public List<Page> getPages() {
if (pages==null) pages=getMany(Page.class, "book");
return pages;
}
}
而 Page.java 是:
@Table(name = "Pages")
public class Page extends Model {
@Column(name = "words")
int words;
@Column(name = "book")
Book book; //ForeignKey of the book it belongs
public Page(){
}
}
我遇到的问题是我想将检索对象时未加载的整个书对象(及其所有子对象)序列化为 JSon(使用 GSon)。
public String toJSon(long id){
Book b = new Select().from(Book.class).where("id = ?", id).executeSingle();
// At this point, the array of pages is obviously empty, and I don't want to hard-call "getPages" because in the future every page will have words, and I would then have to iterate every page, etc..
Gson gson = new GsonBuilder().create();
return gson.toJson(b);
}
如何一次加载 Book 对象及其所有页面?