Only Ancestor queries are allowed inside transactions, how to deal with it?

前端 未结 2 1437
日久生厌
日久生厌 2021-02-15 17:36

I need to do a query inside a Transaction, however I don\'t know the Entity @Id, what I have is a value of a field, like a username but not the ID,

So in o

2条回答
  •  灰色年华
    2021-02-15 18:20

    Without delving into deeper design issues, there are really two options:

    1) Run the query outside of a transaction.

    Objectify (which you tagged this post with) makes it easy to execute non-transactional queries even while inside a transaction. Just spawn a new ofy instance not associated with a transaction and use that to run the query... then go back to working in your transaction. Keep in mind that this does break out of the transaction and could have effects on the integrity of the operation. Often it doesn't matter.

    If you're using Objectify4 you can just run the operation like this:

    ofy.transactionless.load().type(Thing.class).filter("field", value)...etc
    

    2) Use a lookup entity

    This is typically the right answer when dealing with things like usernames. Create a separate entity which maps the username to your User object like this:

    class Username {
        @Id String username;
        Key user;
    }
    

    Use XG transactions to create a Username every time you create a User, and update it if you allow your usernames to change. Now, to perform a transactional lookup of User by username, first lookup the Username and then use that to lookup the User.

提交回复
热议问题