【问题标题】:How to delete a set of Entities using Objectify .ids()如何使用 Objectify .ids() 删除一组实体
【发布时间】:2016-03-25 17:03:04
【问题描述】:

我正在使用 Objectify 从 GAE 读取一组实体:

List<CountStore> myList = ofy().load().type(CountStore.class).list();

然后我过滤并删除 myList 的一些元素。我现在想删除剩余列表中的所有 id。我认为正确的方法是使用 .ids():

ofy().delete().type(CountStore.class).ids(myList);

但这不起作用 - 它会崩溃(见下文),因为它期望 myList 是 Long 或 String。谁能建议删除一组实体的最佳方法?

谢谢!

java.lang.IllegalArgumentException: id 'com.xyz.abc.CountStore@53d71fff' must be String or Long
at com.googlecode.objectify.util.DatastoreUtils.createKey(DatastoreUtils.java:66)
at com.googlecode.objectify.util.DatastoreUtils.createKeys(DatastoreUtils.java:112)
at com.googlecode.objectify.impl.DeleteTypeImpl.ids(DeleteTypeImpl.java:91)
at com.xyz.abc.CounterServlet.doGet(CountrServlet.java:45)

...

【问题讨论】:

  • 在什么情况下不起作用?您的示例是异步删除 - 您可以添加 now() 进行同步操作。
  • 对不起,我的意思是添加删除崩溃 - 请参阅上面的崩溃报告的前几行。
  • 根据您的代码示例,ids() 的参数是 Countstore 的列表 - 它应该是您的实体的 @Id 属性列表,可以是字符串或长整数。跨度>

标签: google-app-engine objectify


【解决方案1】:

感谢您指出只需要一个长 ID 数组。答案真的很简单,就是在过滤要删除的实体时创建一个 ID 的 ArrayList:

  ArrayList<Long> idList = new ArrayList<Long>();

  //Do the Filtering and add IDs to the idList array the delete them all
  ofy().delete().type(CountStore.class).ids(idList).now();

【讨论】:

  • 你也可以ofy().delete().entities(...yourlistofentities...).now()
【解决方案2】:

我已将删除抽象如下:

    public void deleteEntities(List<BaseClass> entities){
        try{
            ofy().delete().entities(entities);
        }catch (Exception ex) {
            logger.error("Exception", ex);
        }
    }

然后转储派生类对象:

    List<DerivedClass> params = receivedFromSomeOtherFunction();
    List<BaseCLass> params2 = new ArrayList<BaseClass>();
    params2.addAll(params);

然后调用deleteEntities如下:

    deleteEntities(params2);

然而,我发现一个缺点是有时这个函数调用需要一些时间来删除所有元素,尽管函数调用会立即返回,这可能是因为它异步删除了对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2021-12-20
    • 2022-08-14
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多