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

北城余情 提交于 2019-12-09 10:10: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 other words, I can't create a Key to do the query. How can I do a query to get an Entity inside a Transaction?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11361008/only-ancestor-queries-are-allowed-inside-transactions-how-to-deal-with-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!