ORMLite createOrUpdate()记录同时保留特定列?

时间:2013-07-23 16:36:17

标签: java android sql database ormlite

我正在使用ORMLite来管理包含数据收集应用程序的查找值列表的数据库表。这些查找值定期从远程服务器更新。但是,我希望能够在创建或更新记录时保留特定列中的数据,因为我希望存储与每个查找值关联的使用计数(特定于设备)。以下是我更新记录的方法:

        //build list of new records
        final List<BaseLookup> rows = new ArrayList<BaseLookup>();
        for (int i = 0; i < jsonRows.length(); i++) {
            JSONObject jsonRow = jsonRows.getJSONObject(i);

            //parse jsonRow into a new BaseLookup object and add to rows
            ...
        }

        //add the new records
        dao.callBatchTasks(new Callable<Void>() {
            public Void call() throws Exception {
                for (BaseLookup row : rows) {
                    //this is where I'd like to preserve the existing
                    //value (if any) of the "usageCount" column

                    Dao.CreateOrUpdateStatus result = dao.createOrUpdate(row);
                }
                return null;
            }
        });

我已经考虑过尝试在循环中单独获取和合并每个记录,但这似乎表现不佳(某些表是几千条记录)。是否有更简单或更集成的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

  

我希望能够在创建或更新记录时保留特定列中的数据,因为我希望存储与每个查找值关联的使用计数(特定于设备)

如果您必须更新JSON数据中的某些列,但又想将usageCount设置为usageCount + 1,那么您有几个选项。

  • 您可以使用dao.updateBuilder();方法和UpdateBuilder类构建更新语句,然后将列更新为新值,将usageCount更新为usageCount + 1,其中id匹配。您应该观察返回值以确保更新行。如果没有,则创建对象。

  • 但是,它更容易:

    1. 从数据库中获取BaseLookup
    2. 如果为null,请调用dao.create()以保留新条目
    3. 否则更新列并增加usageCount
    4. 并使用dao.update(...)
    5. 保存回来