两个标识列

n3h0vuf2  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(221)

我正在使用ormlite,我想知道是否有可能在一个表中有多个标识列。
我有一个表,其中有两个特定的列:id和number。如果id和number相同,我只希望ormlite更新行,否则它应该创建一个新行。我在用这个方法 createOrUpdate .
谢谢。

oalqel3c

oalqel3c1#

通读本文和ormlite文档;多个主键-ormlite
我不能百分之百肯定这个答案。 uniqueCombo = true 似乎是一个很好的猜测,但我不确定,如果事情,如更新和删除仍然工作,然后。你得自己测试一下。

wfveoks0

wfveoks02#

如果id和number相同,我只希望ormlite更新行,否则它应该创建一个新行(我使用的是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 参数,然后只需设置参数并在 createOrUpdate(...) 方法。

相关问题