我正在使用 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/