Reputation: 71
How do i add a record to a child entity in the example below ? For example i have a Employee Record which is name is "Sam". how do i add 2 street adress for sam ?
Guess i have a
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;
// ...
}
Upvotes: 2
Views: 1230
Reputation: 2840
Inserting and retrieving Child Entries can be done in the following way:
Parent class Person
@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
}
Dependent Child Class : Contacts
@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
}
Upvotes: 0
Reputation: 4480
It just works:
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);
Employee being:
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Employee {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
private List<Address> addresses;
...
}
Address being:
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Address {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
...
}
Use @PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
as the class level annotation. Usually you don't need to annotate any other fields but the key, so the @Persistent(mappedBy = "employee")
on the List
is unnecessary.
Btw. I suggest using parametrized collections.
Upvotes: 2