领域自动增量字段示例

Realm Auto Increament field example

我需要在 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?