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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With