2012-05-08 33 views
5

我正在使用本地開發版本的App Engine JDO實現。當我查詢包含其他對象作爲嵌入字段的對象時,嵌入字段將返回爲空。嵌入式JDO字段未通過查詢獲取

例如,可以說這是我堅持的主要對象:

@PersistenceCapable 
public class Branch { 

    @PrimaryKey 
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) 
    private Long id; 

    @Persistent 
    private String name; 

    @Persistent 
    private Address address; 

      ... 
} 

,這我的嵌入對象:

@PersistenceCapable(embeddedOnly="true") 
public class Address { 

    @PrimaryKey 
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) 
    private Long id; 

    @Persistent 
    private String street; 

    @Persistent 
    private String city; 

      ... 
} 

下面的代碼不會檢索嵌入對象:

PersistenceManager pm = MyPersistenceManagerFactory.get().getPersistenceManager(); 

    Branch branch = null; 
    try { 
     branch = pm.getObjectById(Branch.class, branchId); 
    } 
    catch (JDOObjectNotFoundException onfe) { 
     // not found 
    } 
    catch (Exception e) { 
     // failed 
    } 
    finally { 
     pm.close(); 
    } 

有沒有人有這方面的解決方案?我如何檢索分支對象及其嵌入的地​​址字段?

回答

8

我有一個類似的問題,並發現嵌入字段不包括在默認獲取組中。要加載必需的字段,您必須在關閉持久性管理器之前調用getter,或者設置fetch組加載所有字段。

這意味着以下...

branch = pm.getObjectById(Branch.class, branchId); 
pm.close(); 
branch.getAddress(); // this is null 

branch = pm.getObjectById(Branch.class, branchId); 
branch.getAddress(); // this is not null 
pm.close(); 
branch.getAddress(); // neither is this 

所以,你需要改變你的代碼如下:

Branch branch = null; 
try { 
    branch = pm.getObjectById(Branch.class, branchId); 
    branch.getAddress(); 
} 
catch (JDOObjectNotFoundException onfe) { 
    // not found 
} 
catch (Exception e) { 
    // failed 
} 
finally { 
    pm.close(); 
} 

或者,你可以設置你獲取羣組包括所有領域以下...

pm.getFetchPlan().setGroup(FetchGroup.ALL); 
branch = pm.getObjectById(Branch.class, branchId); 
pm.close(); 
branch.getAddress(); // this is not null 
+0

感謝您的及時回答!我會測試這個,並讓你知道它是否有效。 – Chania

+0

如果某個字段位於活動的提取組中,那麼顯然應該提取該字段。如果您認爲不是,那麼爲什麼不提供簡單的測試用例並通過http://code.google.com/p/datanucleus-appengine/issues/list報告?未報告可能意味着沒有人蔘與該項目將知道關於它 – DataNucleus

+0

我不確定這是一個錯誤還是JDO規範的一部分。我記得在JDO規範的某個地方閱讀了嵌入式領域的惰性加載,但現在我找不到它了。 – Cengiz