如何在Google App Engine(Java)中注释嵌入对象的集合?

时间:2010-09-23 03:12:13

标签: google-app-engine jdo

是否可以在Google App Engine(Java)中存储嵌入式类的集合?如果是这样,我将如何注释它?

这是我的班级:

@PersistenceCapable
public class Employee
{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    Key key;

    @Persistent(embeddedElement = "true")
    private List<ContactInfo> contactDetails = new ArrayList<ContactInfo>();

    public void addContactInfo(String streetAddress, String city)
    {
        this.contactDetails.add(new ContactInfo(streetAddress, city));
    }

    public List<ContactInfo> getContactDetails()
    {
        return this.contactDetails;
    }

    @PersistenceCapable
    @EmbeddedOnly
    public static class ContactInfo
    {
        @Persistent
        private String streetAddress;

        @Persistent
        private String city;

        public ContactInfo(String streetAddress, String city)
        {
            this.streetAddress = streetAddress;
            this.city = city;
        }

        public String getStreetAddress()
        {
            return this.streetAddress;
        }

        public String getCity()
        {
            return this.city;
        }
    }
}

这是测试代码:

// Create the employee object

Employee emp = new Employee();

// Add some contact details

emp.addContactInfo("123 Main Street", "Some City");
emp.addContactInfo("50 Blah Street", "Testville");

// Store the employee

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

try
{
    pm.makePersistent(emp);
} 
finally
{
    pm.close();
}

// Query the datastore for all employee objects

pm = PMF.get().getPersistenceManager();

Query query = pm.newQuery(Employee.class);

try
{
    List<Employee> employees = (List<Employee>) query.execute();

    // Iterate the employees

    for(Employee fetchedEmployee : employees)
    {
        // Output their contact details

        resp.getWriter().println(fetchedEmployee.getContactDetails());
    }
}
finally
{
    query.closeAll();
    pm.close();
}

测试代码始终输出'null'。有什么建议吗?

我已尝试将contactDetails列表注释为@Embedded,但DataNucleus增强器引发了异常。我还尝试将defaultFetchGroup =“true”添加到contactDetails列表上的@Persistent注释中(如果它是获取数据的问题),但输出仍然为null。我已经在控制台中检查了员工对象,并且没有任何证据表明在对象上存储了任何联系人详细信息字段,数据存储区中也没有任何独立的ContactInfo对象(不是我期望的那样,给定它们)是嵌入式对象)。

这甚至可以吗?我知道嵌入类的字段存储为实体的属性,因此我可以看到集合scneario中可能出现字段名称冲突,但App Engine docs没有明确表示无法完成。< / p>

2 个答案:

答案 0 :(得分:2)

我不知道您是否还需要答案,但将List放入defaultFetchGroup可以解决这个问题:

@PersistenceCapable
public class Employee
{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    Key key;

    @Persistent(embeddedElement = "true", defaultFetchGroup = "true")
    private List<ContactInfo> contactDetails = new ArrayList<ContactInfo>();

    // Snip...

}

答案 1 :(得分:0)

使用JDO,您可以按照DataNucleus文档进行操作 http://www.datanucleus.org/products/accessplatform_2_2/jdo/orm/embedded.html#Collection 该示例显示了XML,但注释名称大致相同。

GAE / J的插件是否支持这个我不能说,因为它是Google的责任。也许试试吧?