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

前端 未结 2 1445
日久生厌
日久生厌 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:18

    I've had a similar problem, and the simplest method I've come up with is to use one dummy parent entity. Instead of using XG transactions and inserting another Username entity for every other User entity, just create one dummy parent entity and set that as the ancestor of every User entity you create from there on. I think this method saves a lot of space and data management issues.

    0 讨论(0)
  • 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> 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.

    0 讨论(0)
提交回复
热议问题