Riley Lark
Riley Lark

Reputation: 20890

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 populated with an empty string. Is this possible with JDO?

Upvotes: 3

Views: 583

Answers (1)

antony.trupe
antony.trupe

Reputation: 10824

Yes, though not as trivially as you were probably expecting.

Limitations

  1. 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.
  2. 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

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

Upvotes: 2

Related Questions