2014-02-18 60 views
1

GAE official doc我嘗試測試它在我的本地開發環境(單元測試),不幸的是,實體組數總是返回0:獲取實體組計數始終返回0

DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); 
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); 

    Entity entity1 = new Entity("Simple"); 
    Key key1 = ds.put(entity1); 
    Key entityGroupKey = Entities.createEntityGroupKey(key1); 
    //should print 1, but 0 
    showEntityGroupCount(ds, memcacheService, entityGroupKey); 

    Entity entity2 = new Entity("Simple", key1); 
    Key key2 = ds.put(entity2); 
    //should print 2, but still 0 
    showEntityGroupCount(ds, memcacheService, entityGroupKey); 
下面

the doc複製的快速參考:

// A simple class for tracking consistent entity group counts 
class EntityGroupCount implements Serializable { 
    long version; // Version of the entity group whose count we are tracking 
    int count; 
    EntityGroupCount(long version, int count) { 
    this.version = version; 
    this.count = count; 
    } 
} 

// Display count of entities in an entity group, with consistent caching 
void showEntityGroupCount(DatastoreService ds, MemcacheService cache, PrintWriter writer, 
          Key entityGroupKey) { 
    EntityGroupCount egCount = (EntityGroupCount) cache.get(entityGroupKey); 
    if (egCount != null && egCount.version == getEntityGroupVersion(ds, null, entityGroupKey)) { 
    // Cached value matched current entity group version, use that 
    writer.println(egCount.count + " entities (cached)"); 
    } else { 
    // Need to actually count entities. Using a transaction to get a consistent count 
    // and entity group version. 
    Transaction tx = ds.beginTransaction(); 
    PreparedQuery pq = ds.prepare(tx, new Query(entityGroupKey)); 
    int count = pq.countEntities(FetchOptions.Builder.withLimit(5000)); 
    cache.put(entityGroupKey, 
       new EntityGroupCount(getEntityGroupVersion(ds, tx, entityGroupKey), count)); 
    tx.rollback(); 
    writer.println(count + " entities"); 
    } 
} 

有關此問題的任何想法?提前致謝。

+0

嘗試過部署?通常,這些東西在開發服務器上不起作用,但在部署時運行。 –

+0

我認爲你是對的,我忘了我在開發服務器上。謝謝 – July

回答

1

Entities.createEntityGroupKey()由於方法嵌套而被調用兩次。的

showEntityGroupCount(ds, memcacheService, entityGroupKey); 

出現兩次更改爲

showEntityGroupCount(ds, memcacheService, key1); 

和正確的計數顯示(在開發環境反正)。

+0

好,趕上!你是對的,不能相信官方文件是越野車和誤導,無論如何,我應該發現。非常感謝。 – July

+0

我爲找到這個答案感到非常自豪,它採取了一些故障排除,並且我有堅定不移的決心並且不讓這個問題打敗我:-) –