views:

106

answers:

2

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

The Parent entity is Employee

import java.util.List;

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

The Child key is Adress

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

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

    @Persistent
    private String streetAddress;

    // ...
}
+1  A: 

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.

hleinone
Thanks Hleinone
Kerem Pekçabuk
Hi Hleinone.Thanks for your answer.you suggest to use parametrized collections but what is it ? i'am very new to app engine but i have database knowledge.Also why @Persistent(mappedBy = "employee") part is unnecessary ?
Kerem Pekçabuk
Using parametrized collections means that you use List<OfSomeType> instead of just List. About the other question. In a `@PersistenceCapable` class all the fields that are not `static`, `final` or `transient` and are of a persistent type are persisted by default. The `mappedBy` is used for bidirectional relationships and this case propably doesn't need that.
hleinone
A: 

Hello, gwt client needs the source code. So if you use a Key, GWT will complain. Have you got another detailed solution for relationship 1/N without a Key class ?

duke