GreenDAO:ToMany关系导致SQLite查询在UI线程上执行

时间:2016-08-24 08:32:51

标签: android multithreading android-sqlite greendao

当在Entity上定义ToMany关系时,生成的代码如下所示(ProductEntity与MediaEntity有ToMany关系):

/**
 * To-many relationship, resolved on first access (and after reset).
 * Changes to to-many relations are not persisted, make changes to the target entity.
 */
@Generated(hash = 580223476)
public List<MediaEntity> getMedia() {
    if (media == null) {
        final DaoSession daoSession = this.daoSession;
        if (daoSession == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        MediaEntityDao targetDao = daoSession.getMediaEntityDao();
        List<MediaEntity> mediaNew = targetDao._queryProductEntity_Media(productId);
        synchronized (this) {
            if(media == null) {
                media = mediaNew;
            }
        }
    }
    return media;
}

现在,即使我们在后台线程上获取ProductEntity的实例(例如使用自定义Loader),也会在UI线程上调用其getMedia()方法,这将导致第一次调用getMedia()导致的SQLite查询在UI线程上执行。

有没有办法防止这种延迟加载子对象并指示GreenDao解析所有依赖项并在父实体创建/初始化时填充所有字段?

链接到GreenDAO的github页面上的相应支持票证:https://github.com/greenrobot/greenDAO/issues/416

P.S。我们可以在从DaoSession获得ProductEntity之后手动添加对getMedia()的调用,但这不是一个有效的解决方案:太容易出错。

1 个答案:

答案 0 :(得分:0)

正如您所写的那样,通过使用getter在后台线程中预加载来避免懒惰的getter与数据库交谈。没有更好的方法。

有时甚至可以在UI线程中调用单元化的getter。这取决于你的情况。

相关问题