5

我正在使用 App Engine 的 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();
    }

有人对此有解决方案吗?如何检索 Branch 对象及其嵌入的 Address 字段?

4

1 回答 1

6

我遇到了类似的问题,发现默认提取组中不包含嵌入式字段。要加载所需的字段,您要么必须在关闭持久性管理器之前为其调用 getter,要么将获取组设置为加载所有字段。

这意味着以下...

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
于 2012-05-08T06:49:24.167 回答