如何在JDO(Google App Engine)中插入子实体?

时间:2010-06-10 21:11:17

标签: google-app-engine google-cloud-datastore jdo

如何在下面的示例中向子实体添加记录?例如 我有一个员工记录,名字是“Sam”。我如何为山姆添加2个街道地址?

猜猜我有一个

父实体是员工

import java.util.List;

// ...
@Persistent(mappedBy = "employee")
private List<ContactInfo> contactInfoSets;

子键是地址

import com.google.appengine.api.datastore.Key;
// ... imports ...

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

    @Persistent
    private String streetAddress;

    // ...
}

2 个答案:

答案 0 :(得分:2)

它只是起作用:

Employee sam = new Employee("Sam");
List<Address> addresses = new ArrayList<Address>();
addresses.add(new Address("Foo St. 1"));
addresses.add(new Address("Bar Bvd. 3"));
sam.setAddresses(addresses);
persistenceManager.makePersistent(sam);

员工:

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Employee {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    private List<Address> addresses;
    ...
}

地址:

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Address {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    ...
}

使用@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")作为班级注释。通常您不需要注释除键之外的任何其他字段,因此@Persistent(mappedBy = "employee")上的List是不必要的。

顺便说一下。我建议使用参数化集合。

答案 1 :(得分:0)

插入和检索子条目可以通过以下方式完成:

父类人员

@PersistenceCapable(identityType=IdentityType.APPLICATION,detachable = "true")
public class Person {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
Long id ;
@Persistent
String strName;
@Persistent
String phnNumber;
@Persistent
String strEmail;
@Nullable
@Persistent(defaultFetchGroup="true")
@Element(dependent="true")
//When adding Person Contacts would be added as it is dependent. Also while retrieving
// add defaultFetchGroup = true to retrieve child elements along with parent object.
List<Contacts> lstContacts;

// getter and setter methods

}

依赖子类:联系人

@PersistenceCapable(identityType=IdentityType.APPLICATION,detachable = "true")
public class Contacts 
{
@PrimaryKey  
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
Key id;
@Persistent
String email;
@Persistent
String phNumber;
   //getter and setter methods
  }