How to specify the default value for a field in a JDO object for appengine?

I recently added a text box to one of my objects, which cannot be null. I would like to set the default value for it, so that all the objects that I saved before I added the field will be filled with an empty string. Is this possible with JDO?

+3
source share
1 answer

Yes, although not as trivial as you probably expected.

Limitations

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));
    }
  }
}
+2

Source: https://habr.com/ru/post/1779495/


All Articles