【发布时间】:2015-09-22 14:51:00
【问题描述】:
我需要在 android 的 Realm 数据库中添加自动递增键字段。
我怎样才能做到这一点?
这可能吗?
提前致谢。
【问题讨论】:
我需要在 android 的 Realm 数据库中添加自动递增键字段。
我怎样才能做到这一点?
这可能吗?
提前致谢。
【问题讨论】:
Relam 目前不支持 auto_increment
在GitHub看到这个问题
你可以像这样解决问题
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// increment index
Number num = realm.where(dbObj.class).max("id");
int nextID;
if(num == null) {
nextID = 1;
} else {
nextID = num.intValue() + 1;
}
dbObj obj = realm.createObject(dbObj.class, nextID);
// ...
}
}
【讨论】:
Java 绑定还不支持主键,但它在路线图上并且具有高优先级 - 请参阅:https://groups.google.com/forum/#!topic/realm-java/6hFqdyoH67w .作为一种解决方法,您可以使用这段代码来生成密钥:
int key;
try {
key = realm.where(Child_pages.class).max("id").intValue() + 1;
} catch(ArrayIndexOutOfBoundsException ex) {
key = 0; // when there is no object in the database yet
}
我使用singleton factory for generating primary keys 作为更通用的解决方案,具有更好的性能(无需每次都查询max("id"))。
如果您需要更多上下文,请在 Realm Git Hub 中进行长时间讨论:Document how to set an auto increment id?
【讨论】:
PrimaryKeyFactory.getInstance().initialize 对其进行初始化,然后您可以调用PrimaryKeyFactory.getInstance().nextKey 来获取给定类的下一个键
PrimaryKeyFactory.getInstance().initialize,还是应该将它添加到我想要使用的任何给定类中?
onCreate 中调用 initialize,然后在您的逻辑中使用 PrimaryKeyFactory.getInstance().nextKey