2014-09-26 41 views
0

我正在爲每個我輸入的添加命令創建一個實體,但我想知道如何檢查數據存儲區中的重複項?檢查在gae數據存儲區中是否有重複

Entity entity = new Entity("Animal"); 
    entity.setProperty("nameOfAnimal",name_of_animal); 

我要檢查是,如果第二次有其中輸入名稱相同的動物,我如何檢查是否有重複的條目?

回答

0

您可以嘗試通過過濾「nameOfAnimal」屬性並檢查返回的結果來獲取實體。如果結果爲空,則意味着沒有實體。

Filter propertyFilter = 
    new FilterPredicate("nameOfAnimal", FilterOperator.EQUAL, name_of_animal); 
Query q = new Query("Animal").setFilter(propertyFilter); 
PreparedQuery pq = datastore.prepare(q); 
List<Animal> resultList = pq.asList(FetchOptions.Builder.withLimit(1)); 
if(resultList.size() > 0) { 
    // same name exists 
} else { 
    // first entitiy with this name 
} 

該代碼未經測試,但這是主要想法。 Here is the documentation for property filters

0

您可以使用動物的名稱作爲實體的「id」,然後使用get by id來檢查該動物名稱是否存在。

1

根據您要查找的行爲,您有多個選項。

如果您使用nameOfAnimal爲實體的名稱,你可以簡單地嘗試通過密鑰導入實體創建一個新的人之前:如果你不使用nameOfAnimal爲重點

Key animalKey = KeyFactory.createKey("Animal", "fox"); 
Entity fox; 
try { 
    fox = datastoreService.get(animalKey); 
    // no exception thrown so fox already exists 
    throw new RuntimeException("Animal already exists!"); 
} 
catch(EntityNotFoundException e) { 
    // no duplicates, so can create 
    fox = new Entity(animalKey); 
    fox.setNoise("unknown"); 
    datastoreService.put(fox); 
} 

,你可以使用Query("Animal")而不是get()(如在來自eluleci的回答中)。

無論哪種方式,請注意那裏有潛在的競爭條件。如果你想使它安全,你需要將它包裝在一個transaction,否則你可能會發現兩個線程競爭創建第一個狐狸(例如),一個潛在覆蓋另一個。

相關問題