How to load entire object (with lists) using ActiveAndroid

I have this simple model:

@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;
    }
}

      

And 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(){

    }
}

      

The problem is I want to JSon serialize (using GSon) the entire book object (with all its children) that are not loaded when the object is retrieved.

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);
}

      

How can I load the Book object with all its pages at the same time?

+3


source to share





All Articles