ORMLite插入或替换

x-t*_*eme 6 sqlite android ormlite

我在我的Android应用程序中使用ORMLite,有些情况下我需要sqlite的INSERT OR UPDATE功能.我知道ORMLite有,createOrUpdate但它不适用于我的特定情况.

我将用一个例子解释我的案例.我有两个表A&B.它们之间具有多对多关系,使用单独的映射表表示M.表AB手动生成的主键和M用途generatedId = true.两列在M那家商店的外键A&B已经uniqueCombo = true对他们的设置.因此,当我从后端获取记录(作为JSON)M时,当我尝试调用时,它已经存在,createOrUpdate它将在UNIQUE约束时失败.原因是

public CreateOrUpdateStatus createOrUpdate(T data) throws SQLException {
    if (data == null) {
        return new CreateOrUpdateStatus(false, false, 0);
    }
    ID id = extractId(data);
    // assume we need to create it if there is no id
    if (id == null || !idExists(id)) {
        int numRows = create(data);
        return new CreateOrUpdateStatus(true, false, numRows);
    } else {
        int numRows = update(data);
        return new CreateOrUpdateStatus(false, true, numRows);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面所看到的,如果id模型中没有要持久化,则会执行更新语句,因为UNIQUE约束会失败,但由于该id列是自动生成的,我不知道这一点(我可以查询表)使用这个独特的组合然后找到id,但在我的架构中有很多这样的表,并且为所有表执行此操作的自定义逻辑将是一场噩梦!!)

为了解决这个问题,我计划使用sqlite INSERT OR REPLACE,它会在冲突时删除现有记录并将其替换为新记录.来自sqlite docs

When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes
pre-existing rows that are causing the constraint violation prior to inserting or 
updating the current row and the command continues executing normally
Run Code Online (Sandbox Code Playgroud)

这是我想实现它的方式 - 让ORMLite准备一个INSERT语句,然后替换INSERTINSERT OR REPLACE然后执行该语句.我的问题是ORMLite中是否有任何钩子可以让我这样做(得到INSERT声明)?