【问题标题】:Realm Auto Increament field example领域自动增量字段示例
【发布时间】:2015-09-22 14:51:00
【问题描述】:

我需要在 android 的 Realm 数据库中添加自动递增键字段。 我怎样才能做到这一点? 这可能吗?

提前致谢。

【问题讨论】:

    标签: android realm


    【解决方案1】:

    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);
             // ...
        }
    }
    

    【讨论】:

    【解决方案2】:

    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 来获取给定类的下一个键
    • 那么我可以在我的应用程序的 onCreate 中添加一次PrimaryKeyFactory.getInstance().initialize,还是应该将它添加到我想要使用的任何给定类中?
    • 是的,在 onCreate 中调用 initialize,然后在您的逻辑中使用 PrimaryKeyFactory.getInstance().nextKey
    • 甜蜜的 kotlin 代码:val id = realm.where(MessageBean::class.java).max("id")?.toInt()?.plus(1) ?: 0
    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多