GreenDao之Identity scope and session “cache”

原文http://greendao-orm.com/documentation/sessions/

        問題:

DaoMaster dm = AppContext.getDaoMaster(ctx);
DaoSession ds = dm.newSession(IdentityScopeType.Session);

        如果傳入的是IdentityScopeType.Session,同樣的查詢只會執行一次,查詢結果對象List保存在內存裏會重複使用。會導致的問題是如果List對象屬性改變,未持久化它,再次做query,不會從數據庫查詢,只是緩存中的結果。會導致與數據庫表數據不一致。

       解決辦法,再次執行查詢之前執行ds.clear();方法。或者在這種情況下之不保留緩存,用IdentityScopeType.None。

<span style="white-space:pre">	</span>public List<Label> queryLabels(){
		DaoSession ds = AppContext.getDaoSession(ctx);
//		//clear the cache,requery the data from database table, not from the memory.
		ds.clear();
		
		QueryBuilder<Label> qb = ds.getLabelDao().queryBuilder();
		qb.where(LabelDao.Properties.Deleted.eq(false));
		List<Label> labels = qb.list();
		if(labels.size()<showNum){
			Label entity = new Label(null, "添加標籤", null, false, null, null, true, false);
			labels.add(entity);
		}

		
		return labels;
	}

或者用IdentityScopeType.None創建DaoSession


<span style="white-space:pre">	</span>private DaoSession getDaoSession(IdentityScopeType scope){
		if(scope == IdentityScopeType.Session){
			DaoSession ds = AppContext.getDaoSession(ctx);
			return ds;
		}else{
			DaoMaster dm = AppContext.getDaoMaster(ctx);
			DaoSession ds = dm.newSession(IdentityScopeType.None);
			return ds;
		}
	}


發佈了83 篇原創文章 · 獲贊 17 · 訪問量 103萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章