How can I specify a default value for a field in a JDO entity on appengine?
I recently added Text field to one of my Entities that cannot be null. I'd like to set a default value for it, so that all of the Entities that I stored before I added the field will be populat开发者_JAVA技巧ed with an empty string. Is this possible with JDO?
Yes, though not as trivially as you were probably expecting.
Limitations
- Will time out if it takes more then 30 seconds, unless you run it as a task, in which case it will time out if it takes more then 10 minutes.
- There's no smarter way to get only the entities that need updated since you can't query on a property that doesn't exist.
Workarounds
- You'll want to look into the appengine-mapreduce project to get an implementation that can complete with more then 10 minutes wall-clock time.
- None known.
Code
void updateNullBarField() {
final Text DEFAULT_BAR = new Text("bar");
PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
PersistenceManager pm = pmfInstance.getPersistenceManager();
Query query = pm.newQuery(Foo.class);
@SuppressWarnings("unchecked")
Collection<Foo> foos = pm.detachCopyAll((List<Foo>) query.execute());
for (Foo foo : foos) {
if (foo.bar == null) {
foo.bar = DEFAULT_BAR;
pm.detachCopy(pm.makePersistent(foo));
}
}
}
精彩评论