One-to-many relationship with JDO in Google App Engine
Posted
by Marvin
on Stack Overflow
See other posts from Stack Overflow
or by Marvin
Published on 2010-06-15T19:19:23Z
Indexed on
2010/06/15
19:22 UTC
Read the original article
Hit count: 340
google-app-engine
|jdo
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.
© Stack Overflow or respective owner