开发者

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

  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));
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜