事务内部仅允许祖先查询,如何处理呢? [英] Only Ancestor queries are allowed inside transactions, how to deal with it?

查看:85
本文介绍了事务内部仅允许祖先查询,如何处理呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Transaction内部进行查询,但是我不知道Entity @Id,我拥有的是字段的值,例如用户名而不是ID

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,

因此,换句话说,我无法创建Key来执行查询.如何进行查询以获取Transaction中的实体?

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)在事务外部运行查询.

1) Run the query outside of a transaction.

Objectify(您在其中标记了这篇文章)使即使在事务内部也很容易执行非事务性查询.只需生成一个与事务无关的新ofy实例,然后使用该实例来运行查询...然后返回到您的事务中.请记住,这确实会中断事务,并且可能会影响操作的完整性.通常并不重要.

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.

如果您使用的是Objectify4,则可以像这样运行操作:

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

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

2)使用查找实体

在处理用户名之类的问题时,这通常是正确的答案.创建一个单独的实体,将用户名映射到您的User对象,如下所示:

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;
}

每次创建用户时,使用XG事务创建一个用户名,如果允许您更改用户名,请更新该用户名.现在,要按用户名执行用户的事务性查找,请先查找用户名,然后使用它来查找用户.

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.

这篇关于事务内部仅允许祖先查询,如何处理呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆