【问题标题】:Writing objectify and datastore entities in the same transaction在同一事务中编写 objectify 和 datastore 实体
【发布时间】:2017-04-28 08:44:04
【问题描述】:

我正在尝试在同一个实体组中编写两个实体,一个通过 objectify,另一个通过低级数据存储 api。我创建了一个数据存储事务来执行此操作。我的代码如下所示 -

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

Transaction transaction = datastore.beginTransaction();

try {
  Summary summary = Ofy.ofy().load().key(com.googlecode.objectify.Key.create(parent)).now();
  // Change summary
  Ofy.ofy().save().entity(summary).now();
  Key key = KeyFactory.createKey(parent, "Data", id);

  Entity entity = new Entity(key);
  // add stuff to entity
  datastore.put(entity);
  transaction.commit();
} finally {
  if (transaction.isActive()) {
    transaction.rollback();
  }
}

但是,我最近遇到了一些数据不一致的情况,如果此事务不能保证两个实体的事务更新,则可以解释这一点。我的问题是,交易应该以这种方式进行吗?

根据此处的最后一个常见问题条目 - https://github.com/objectify/objectify/wiki/FrequentlyAskedQuestions,我们可以在事务中混合对象化和数据存储写入,但代码示例可能使用对象化事务。这是唯一的方法吗?

【问题讨论】:

    标签: google-app-engine google-cloud-datastore objectify


    【解决方案1】:

    我能够在测试中重现该场景,确实我们无法从 datastore-transactions 进行 objectify 更新,但我们可以从 objectify-transactions 进行 datastore-updates。

    所以以下工作 -

    final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    
    Ofy.ofy().transact(new Work<Void>() {
      @Override
      public Void run() {
        Summary summary = Ofy.ofy().load().key(com.googlecode.objectify.Key.create(parent)).now();
        // Change summary
        Ofy.ofy().save().entity(summary).now();
        Key key = KeyFactory.createKey(parent, "Data", id);
    
        Entity entity = new Entity(key);
        // add stuff to entity
        datastore.put(entity);
        return null;
      }
    });
    

    【讨论】:

    • 这是正确的。如果您自己管理交易,它将是与 Objectify 使用的交易不同的交易。真的没有理由手动执行交易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多