为什么我得到只允许祖先查询内部交易错误 [英] Why do I get Only ancestor queries are allowed inside transactions error

查看:99
本文介绍了为什么我得到只允许祖先查询内部交易错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  boolean r = ofy()。transact(new Work< Boolean>(){

@Override
public Boolean run(){
访问visit = ofy()。load().type(Visit.class)
.filter(Visit.USER_ID,userID)
.filter(Visit.VENUE_ID,venueID).first() .get();

if(visit == null)
return false;

visit.setLastRequestDate(new Date(timestamp));

ofy()。save()。entity(visit).now();
return true;
}
});

而我得到


java.lang.IllegalArgumentException:仅在事务内允许祖先查询。

用于 get() call。

为什么?我只在这个事务中查询访问实体。
我在交易中这样做,因为我希望所有这些都是作为原子操作来执行的。

解决方案

无法在事务内执行无祖先查询。您可以在没有交易的情况下执行此操作,也可以使用get替换查询。



您可以执行的操作最接近:

  • 使用没有事务的无祖先查询获取实体。记得实体的关键。

  • 开始交易。

  • 通过密钥获取实体。查询条件仍然适用(=属性的值仍然与查询条件中的值相同)。通过这种方式,您可以确定实体自查询以来未发生变化。

  • 更改&保存实体。提交交易。


  • boolean r = ofy().transact(new Work<Boolean>() {
    
            @Override
            public Boolean run() {
                Visit visit = ofy().load().type(Visit.class)
                        .filter(Visit.USER_ID, userID)
                        .filter(Visit.VENUE_ID, venueID).first().get();
    
                if (visit == null)
                    return false;
    
                visit.setLastRequestDate(new Date(timestamp));
    
                ofy().save().entity(visit).now();
                return true;
            }
        });
    

    and I get

    java.lang.IllegalArgumentException: Only ancestor queries are allowed inside transactions.

    for the line with the get() call.
    why? I'm only querying Visit entity in this transaction. I'm doing this in a transaction, because I want all this to be performed as atom operation.

    解决方案

    No way to do ancestor-less query inside a transaction. Either you do it without transactions or replace query with get.

    The closest that you can do is:

    1. Get entity with ancestor-less query without transaction. Remember key of the entity.
    2. Start transaction.
    3. Get entity via the key.
    4. Check that query condition still applies (= properties still have the same values as in query conditions). This way you can be sure entity was not changed since you did the query.
    5. Change & save entity. Commit transaction.

    这篇关于为什么我得到只允许祖先查询内部交易错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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