2012-05-08 32 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