I am trying to maintain a one-to-many relationship with bidirectional navigation in GAE using JDO.
I manually add the class Contactto User, and I expect that at the end there Contactwill be a reference to the parent User.
- If I configure this manually before I save the parent, I will get an exception:
org.datanucleus.store.appengine.DatastoreRelationFieldManager.checkForParentSwitch(DatastoreRelationFieldManager.java:204) - After the persistence of the object, the
Userparent link is not updated. - After the object
Contactis retrieved from the datastore using the key, the parent link is not updated.
I do not understand where my mistake is.
package test;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.google.appengine.api.datastore.Key;
public class DatastoreJdoTest extends LocalServiceTestCase {
@Autowired
@Qualifier("persistenceManagerFactory")
PersistenceManagerFactory pmf;
@Test
public void testBatchInsert() {
Key contactKey;
PersistenceManager pm = pmf.getPersistenceManager();
try {
pm.currentTransaction().begin();
User user = new User();
Contact contact = new Contact("contact1");
user.contacts.add(contact);
Assert.assertNull(contact.key);
pm.makePersistent(user);
Assert.assertNotNull(contact.key);
pm.currentTransaction().commit();
contactKey = contact.key;
} finally {
if (pm.currentTransaction().isActive()) {
pm.currentTransaction().rollback();
}
}
Contact contact2 = pm.getObjectById(Contact.class, contactKey);
Assert.assertNotNull(contact2);
Assert.assertNotNull(contact2.user);
}
}
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
class User {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Key key;
@Persistent
public String name;
@Persistent
public List<Contact> contacts = new ArrayList<Contact>();
}
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
class Contact {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
Key key;
@Persistent
public String contact;
@Persistent(mappedBy = "contacts", dependent = "true")
public User user;
public Contact(String contact) {
this.contact = contact;
}
}