【问题标题】:How to set primary key auto increment in realm android如何在领域android中设置主键自动增量
【发布时间】:2017-03-03 15:55:00
【问题描述】:

我想为我的表设置主键自动递增。

这是我的课。我已经设置了主键,但我希望它是自动递增主键。

public class users extends RealmObject {

@PrimaryKey
private int id;
private long icn;
private String name;
private String email;
private String password;
private int phone;

public String getName() {
    return name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public long getIcn() {
    return icn;
}

public void setIcn(long icn) {
    this.icn = icn;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public int getPhone() {
    return phone;
}

public void setPhone(int phone) {
    this.phone = phone;
}

}

提前致谢。

【问题讨论】:

  • 我正在寻找领域中的内置属性,它会像其他数据库一样自动递增。
  • 你不会发现它,因为它不存在。主要是因为它可以毫不费力地在 6 行中完成,所以它从来都不是高优先级。
  • Realm 是对象数据库——它存储对象图。 Tables 索引表时使用主键,没有这种东西,Realm 使用@PrimaryKey 是为了索引方便
  • @AlexShutov 好吧,主键对于识别对象以便以后更新它们很重要,并且对于新发布的 Realm Object Server 的同步逻辑非常重要。但是您设置为主键的内容几乎取决于您。

标签: android realm


【解决方案1】:

我用这个。

public static int nextID(Class table) {
        return instance.realm.where(table).findAll().max("id").intValue() + 1;
    }

所以我想增加 Class Person Id,

netID(Person.class);

【讨论】:

    【解决方案2】:

    一个简短的答案可以是这样的:

        Person person = new Person();
        person.setName("UserName");
    
        realm.beginTransaction();
    
        Number newId = realm.where(Person.class).max("id");
        person.setId(newId.intValue()+1);
    
        realm.copyToRealm(person);
        realm.commitTransaction();
    

    【讨论】:

      【解决方案3】:

      在科特林中

      我的界面

      fun getRegistroIdentity(): Int
      

      我的方法

      class RegistroOver(private val realm: Realm) : RegistroImplementation {
      
      override fun getRegistroIdentity(): Int {
          val registro = realm.where(Registro::class.java).max("id")
          val result: Int
          result = if (registro == null) {
              1
          } else {
              registro.toInt() + 1
          }
          return result
      }}
      

      :)

      【讨论】:

        【解决方案4】:

        有一个例子可以做一个序列来实现主键id的自动递增:

        https://raw.githubusercontent.com/505aaron/realm-migration-example/master/realm/sequencer.js

        const sequencer = (realmInstance, schema, props) => new Promise((resolve, reject) => {
          let saved;
        
          try {
            realmInstance.write(() => {
              const obj = { ...props };
        
              if (typeof obj.id === 'undefined') {
                let seq = realmInstance.objects('Sequence').filtered(`name = "${schema}"`)[0];
                if (typeof seq === 'undefined') {
                  seq = realmInstance.create('Sequence', { name: schema, value: 0 });
                }
                obj.id = seq.next();
              }
              saved = realmInstance.create(schema, obj, true);
        
              resolve({ ...saved });
            });
          } catch (e) {
            reject(e);
          }
        });
        
        export default sequencer;
        

        【讨论】:

          【解决方案5】:

          对于原生反应

          ...
          // this is the part where you are saving the newItem
          realm.write(() => {
              // handle the id
              let id: any = realm.objects(this.Schema).max("id");
              newItem.id = id === undefined ? 1 : id++;
              realm.create(this.Schema, newItem);
              resolve(newItem);
          });
          

          【讨论】:

          • 必须是 ++id 而不是 id++ 否?
          【解决方案6】:

          就我个人而言,我将 id 设置为 Unix 时间值。我知道不是增量而是独一无二的?

          (int) System.currentTimeMillis() / 1000;
          

          【讨论】:

          • 通过某种方式,如果在一秒钟内插入 2 条记录,则会抛出错误。
          • @MaazPatel 嗯,这是真的。我将尝试模拟您的评论,因为在我的应用程序中不会同时插入 2 个项目。
          • 你不应该把它转换成一个 int... 那么它是一个更好的选择。
          • 如果用户将时间改回一小时左右怎么办?
          【解决方案7】:

          这是一个古老且已回答的问题,但我想发布另一个我使用的解决方案。 你可以这样做:

          Realm realm = Realm.getDefaultInstance();
          // Realm transaction
          realm.executeTransactionAsync(new Realm.Transaction() { 
              @Override
               public void execute(Realm bgRealm) {
                   // Get the current max id in the users table
                   Number maxId = bgRealm.where(users.class).max("id");
                   // If there are no rows, currentId is null, so the next id must be 1
                   // If currentId is not null, increment it by 1
                   int nextId = (maxId == null) ? 1 : maxId.intValue() + 1;
                   // User object created with the new Primary key
                   users user = bgRealm.createObject(users.class, nextId);
                   // Now you can update your object with your data. The object will be
                   // automatically saved in the database when the execute method ends
                   // ...
                   // ... 
              }
          }
          

          【讨论】:

            【解决方案8】:

            好吧,@PrimaryKey 只是表示该字段是一个键。但是您在创建对象并将其复制到 Realm 时自行设置。考虑使用 UUID.random(),而不是手动增加它。 (如评论中的回答):Realm Auto Increament field example

            【讨论】:

            【解决方案9】:

            在事务中,您始终可以可靠地访问当前的最大 ID,在此基础上您可以递增该 ID,并将其用作下一个 ID 的基础。

             realm.executeTransaction(new Realm.Transaction() { // must be in transaction for this to work
                 @Override
                 public void execute(Realm realm) {
                     // increment index
                     Number currentIdNum = realm.where(users.class).max(usersFields.ID);
                     int nextId;
                     if(currentIdNum == null) {
                        nextId = 1;
                     } else {
                        nextId = currentIdNum.intValue() + 1;
                     }
                     users user = new users(); // unmanaged
                     user.setId(nextId);
                     //...
                     realm.insertOrUpdate(user); // using insert API
                 }
             }
            

            【讨论】:

            • 顺便说一句,这对于同步领域来说有点棘手,通常最好使用随机 UUID。或支持 RealmCounter。
            • @EpicPandaForce 在将 JSON 直接写入领域并且想要自动生成主键值时,您如何处理这个问题?如果您可以添加第二个注释,例如 RealmAutoGenerate,那就太好了
            • 如果您使用createAllFromJson 等方法,您可能无法自动执行此操作。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-07-13
            • 2017-08-13
            • 1970-01-01
            • 2014-12-02
            • 1970-01-01
            • 2011-12-04
            • 1970-01-01
            相关资源
            最近更新 更多