简体   繁体   English

如何使用 Objectify 在 Java GAE 中的无效 function 中设置事务?

[英]How do I set up a transaction within a void function in Java GAE using Objectify?

I am trying to set up a transaction in a void function in Java using Objectify.我正在尝试使用 Objectify 在 Java 中的 void function 中设置事务。 This is the wiki documentation.这是维基文档。

import static com.googlecode.objectify.ObjectifyService.ofy;

Thing th = ofy().transact(() -> {
    Thing thing = ofy().load().key(thingKey).now();
    thing.modify();
    ofy().save().entity(thing);
    return thing;
});

I've read the docs but this is still unclear to me.我已经阅读了文档,但这对我来说仍然不清楚。 How could I implement this transaction in this function?我怎样才能在这个 function 中实现这个事务?

public void addForm(
        String name, String link)
    throws Exception
    {
        Form newForm = new Form(name, link);
        ofy().save().entity(newForm).now();
    }

I need to be able to call addForm so I can't wrap that function inside the transaction since I won't be able to call it again.我需要能够调用 addForm 所以我不能将 function 包装在事务中,因为我将无法再次调用它。 Is that correct?那是对的吗?

I suppose this part of wiki is form here .我想这部分 wiki 是在这里形成的。 In the same documentation there is an example of transaction in void function ( I know it's different topic, however code is proper):在同一文档中,有一个void function 中的事务示例(我知道这是不同的主题,但是代码是正确的):

public void doSomeWork() {
    ofy().transact(() -> {
        doSomeMoreWork();
    });
}

So translating this to the addForm this should be something like:所以把它翻译成addForm这应该是这样的:

public void addForm(String name, String link)
    throws Exception
    {
        ofy().transact(() -> {
            Form newForm = new Form(name, link);
            ofy().save().entity(newForm).now();
        }
    }

I don't think there is a point to create transaction for one database operation, however I guess you want to add more in future.我认为没有必要为一个数据库操作创建事务,但是我想您将来想添加更多。 You can call the function any time you want.您可以随时致电 function。

I hope it will help!我希望它会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM