Loading a collection of Enums with Google app engine datastore
-
19-09-2019 - |
Question
I am using the Goole app engine datastore with Java and trying to load an Object with a List of Enums. Every time I load the object the List is null. The object is
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class ObjectToSave {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private List<AnEnum> anEnumList;
//public getters and setters
}
The enum is simple
public enum AnEnum {
VALUE_1,
VALUE_2;
}
The code to save it is
ObjectToSave objectToSave = new ObjectToSave();
List<AnEnum> anEnumList = new ArrayList<AnEnum>();
anEnumList.add(AnEnum.VALUE_1);
objectToSave.setAnEnumList(anEnumList);
PersistenceManager pm = pmfInstance.getPersistenceManager();
try {
pm.makePersistent(objectToSave);
} finally {
pm.close();
}
The code to load it is
PersistenceManager pm = pmfInstance.getPersistenceManager();
try {
Key key = KeyFactory.createKey(ObjectToSave.class.getSimpleName(), id);
ObjectToSave objectToSave = pm.getObjectById(ObjectToSave.class, key);
} finally {
pm.close();
}
I can view the data in the datastore using http://localhost:8080/_ah/admin and can see my List has been saved but it is not there when the object is loaded.
I created my project with the Eclipse plugin and haven't made any changes to the datastore settings as far as I know. So why id my Enum list null?
Solution
Yes but your List field is not in the default fetch group at loading so hence is not loaded. Read JDO Fetch Groups. You could add it to the DFG, or enable a custom fetch group, or just "touch" the field before closing the PM.
--Andy (DataNucleus)
OTHER TIPS
How are you creating an instance of ObjectToSave? The default value of all instance variable reference types is null, so unless you have (additional) code to create an instance of List<AnEnum>
and assign it to anEnumList
, null would be expected.