One-to-many relationship with JDO in Google App Engine
- by Marvin
I've followed the GAE docs on setting up one-to-many relationship in JDO but I'm still having trouble in retrieving the collection data back. I have no problem getting the other non-collection fields back. Here are my classes:
@PersistenceCapable
public class User{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String uniqueId;
@Persistent
private String email;
@Persistent
private List<Address> addresses = new ArrayList<Address>() ;
...
}
@PersistenceCapable
public class Phone{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String number;
...
}
public class UserDaoImpl implements UserDao {
public void insertUser(User user) {
if(user.getKey() == null) {
com.google.appengine.api.datastore.Key key = KeyFactory.createKey(User.class.getSimpleName(), user.getEmail());
user.setKey(key);
}
PersistenceManager pm = PersistenceManagerWrapper.getPersistenceManager();
notNull(user);
try {
pm.makePersistent(user);
} finally {
pm.close();
}
}
@SuppressWarnings("unchecked")
public User getUser(String uniqueId) {
PersistenceManager pm = PersistenceManagerWrapper.getPersistenceManager();
Query query = pm.newQuery(User.class);
query.setFilter("uniqueId == uniqueIdParam");
query.declareParameters("String uniqueIdParam");
User user = null;
try {
List<User> users = (List<User>)(query.execute(uniqueId));
//TODO abstract this
if(users.size() > 0)
user = users.get(0);
} finally {
pm.close();
}
return user;
}
}
public class UserDaoImplTest {
@Test
public void getUserTest() {
User user = createTestUser();
assertNotNull("The user object should not be null", user);
userDao.insertUser(user);
User returnedUser = userDao.getUser(TEST_USER_ID);
assertNotNull("The returnedUser object should not be null", returnedUser);
Assert.assertPropertyEqualsExcludeProperties("User Object", user, returnedUser, "");
}
}
When I run the test, all the properties for User is populated but the list of Phone if I get is empty.