java - 两个身份列

标签 java android ormlite

我正在使用 ORMlite,我想知道是否可以在一个表中拥有多个标识列。

我有一个表,其中包含两个特定列:ID 和 Number。我希望 ORMlite 仅在 ID 和 Number 相同时更新行,否则它应该创建一个新行。我正在使用方法createOrUpdate

谢谢。

最佳答案

I want ORMlite only to update the row if ID and Number are the same, otherwise it should create a new row (I am using the Method createOrUpdate).

是的,您将无法使用createOrUpdate(...)但是您应该能够添加自己的 DAO 方法来很好地模拟它。如果ID不会是唯一的,那么您需要创建另一个 ID 字段作为身份并使用您的 ID作为另一个字段,可以使用 uniqueCombo限制。

@DatabaseField(generatedId = true)
private int uniqueId;
// not the id field because it is not unique
@DatabaseField
private int id;
@DatabaseField
private int number;

在您的 DAO 类中,覆盖 BaseDaoImpl类并覆盖 createOrUpdate(...)方法。它应该做类似的事情:

public CreateOrUpdateStatus createOrUpdate(Foo data) throws SQLException {
    QueryBuilder<Foo, Integer> qb = queryBuilder();
    // NOTE: id here is not the identity field
    qb.where().eq("id", data.id).and().eq("number", data.number);
    Foo existing = qb.queryForFirst();
    if (existing == null) {
        int numRows = create(data);
        return new CreateOrUpdateStatus(true, false, numRows);
    } else {
        int numRows = update(data);
        return new CreateOrUpdateStatus(false, true, numRows);
    }
}

作为一项优化,您可以使用 ThreadLocalSelectArg 预先创建该查询。 id 和 number 参数的参数,然后只需设置参数并在 createOrUpdate(...) 中运行查询方法。

关于java - 两个身份列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16956404/

相关文章:

java - Spring @Transactional 注解不回滚

java - Serializable/Cloneable/... 的惯用设计在 Scala 中看起来如何?

javascript - React Native - "undefined is not an object (evaluating ' MyApp.navigation.openDrawer')

android - 无法使用 HttpClient 从 Android 设备相机发布图像

Android ORMLite 没有这样的表异常

java - 如何使用 for 循环创建表数组?

java - 未引用的方法是否包含在最终的可执行文件中?

android - 在 Android 上将表从一个数据库插入到另一个数据库的 ORMLite 问题

java - 将 id 存储在 spinner 控件中

java - 如何将 Android 库项目转换为外部 JAR?