簡體   English   中英

子數據存儲區實體的鍵返回為null

[英]key of child datastore entity returns as null

我有一個典型的Person-Address實體關系。 在查詢數據存儲區中的Person后,然后查詢Person以獲取地址密鑰。 鍵(即addrKey ,請參見下文)始終返回為null。 但是我看一下數據存儲區,看到Person和Address實體,以及它們的鍵。 因此,很明顯, Key addrKey = (Key) person.getProperty("address")Key addrKey = (Key) person.getProperty("address")並沒有執行我認為應該做的事情。 任何想法如何解決這一問題?

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Map<Key, Entity> entities = datastore.get(keys);

    List<Person> result = new ArrayList<Person>();
    Iterator<Entry<Key, Entity>> it = entities.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Key, Entity> ent = it.next();

        final Entity person = ent.getValue();
        Key key = person.getKey();
        name = (Long) person.getProperty("name");
        Address address = getAddress(datastore, person);

...
    }


private Address getAddress(DatastoreService datastore, Entity person) {
    Key addrKey = (Key) person.getProperty("address");
    try {
        Entity d = datastore.get(addrKey);
        String street = (String) d.getProperty("street");
…
}

我的猜測是您同時保留住地址和個人。 但是,默認情況下,地址在保留之前具有不完整的密鑰(假設您依賴密鑰的自動ID生成)。 因此,您親自存儲了一個不完整的密鑰。 並且使用不完整密鑰進行的提取將不起作用。

我寫了一個快速測試用例:

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public class TempTest extends PersistenceTestHelper {

  @Test
  public void testStackOverflow() throws Exception {

    Entity address = new Entity("address", 1);
    address.setProperty("street", "my street");

    Entity person = new Entity("person", 1);
    person.setProperty("addressKey", address.getKey());
    System.out.println(person);

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(person);
    datastore.put(address);

    Entity personFromDatastore = datastore.get(person.getKey());
    Key addressKey = (Key) personFromDatastore.getProperty("addressKey");
    Entity addressFromDatastore = datastore.get(addressKey);
    System.out.println("fetched street: " + addressFromDatastore.getProperty("street"));

    address = new Entity("address");
    System.out.println("Address with incomplete key: " + address.getKey());
    try {
      addressFromDatastore = datastore.get(address.getKey());
    } catch (IllegalArgumentException e) {
      System.out.println(e);
    }
  }

}

這是輸出:

<Entity [person(1)]:
    addressKey = address(1)
>
fetched street: my street
Address with incomplete key: address(no-id-yet)
java.lang.IllegalArgumentException: address(no-id-yet) is incomplete.

如果我錯了,那么很高興理解為什么您的示例中有一個try catch。 而且,在投入前和事后獲取時,Person實體和Address實體的打印輸出也會很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM